USACO hamming

考试周终于过去了一半,可以继续写USACO了。

先来看一下题目吧。

Hamming Codes
Rob Kolstad

Given N, B, and D: Find a set of N codewords (1 <= N <= 64), each of length B bits (1 <= B <= 8), such that each of the codewords is at least Hamming distance of D (1 <= D <= 7) away from each of the other codewords. The Hamming distance between a pair of codewords is the number of binary bits that differ in their binary notation. Consider the two codewords 0x554 and 0x234 and their differences (0x554 means the hexadecimal number with hex digits 5, 5, and 4):

        0x554 = 0101 0101 0100
0x234 = 0010 0011 0100
Bit differences: xxx xx

Since five bits were different, the Hamming distance is 5.

PROGRAM NAME: hamming

INPUT FORMAT

N, B, D on a single line

SAMPLE INPUT (file hamming.in)

16 7 3

OUTPUT FORMAT

N codewords, sorted, in decimal, ten per line. In the case of multiple solutions, your program should output the solution which, if interpreted as a base 2^B integer, would have the least value.

SAMPLE OUTPUT (file hamming.out)

0 7 25 30 42 45 51 52 75 76
82 85 97 102 120 127

这条题目不难,由于数据量很小,因此使用的方法是直接遍历。

/**
ID: njuwz151
TASK: hamming
LANG: C++
*/
#include <iostream>
#include <cstdio> using namespace std; const int maxn = ; int count(int a, int b); int main() {
freopen("hamming.in", "r", stdin);
freopen("hamming.out", "w", stdout); int n, b, d;
cin >> n >> b >> d; int result[ << maxn];
result[] = ;
int n_ptr = ;
for(int i = ; i < ( << b); i++) {
if(n_ptr > n) {
break;
}
bool can_add = true;
for(int j = ; j < n_ptr; j++) {
if(count(i, result[j]) < d) {
can_add = false;
break;
}
}
if(can_add) {
result[n_ptr] = i;
n_ptr++;
}
}
for(int i = ; i < n - ; i++) {
cout << result[i];
if((i + ) % ) {
cout << " ";
} else {
cout << endl;
}
}
cout << result[n - ] << endl;
} int count(int a, int b) {
int result = ;
for(int i = ; i < maxn; i++) {
if(((a>>i) & ) != ((b>>i) & )) {
result++;
}
}
return result;
}
上一篇:初学acm感想


下一篇:大数据时代科研不能再"两头花钱"