一.题目描述
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
二.题目分析
核心思路是从0开始从小到大枚举,当与现有的集合中的数都满足汉明距离要求时,便加入集合。
三.代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int set[64],N,B,D;
int dis(int x,int y) //按照二进制异或求解汉明距离
{
int cn=0;
while(x||y)
{
if(x%2!=y%2)
cn++;
x /=2;
y /=2;
}
return cn;
}
int check(int a,int n) //判断新元素与set中现有的n个元素是否满足汉明距离要求
{
int i;
for(i=0;i<n;i++)
{
if(dis(a,set[i])<D)
return 0;
}
return 1;
}
int main()
{
int i,j,start,end;
FILE *in=fopen("hamming.in","r"),*out=fopen("hamming.out","w");
if(!in||!out)
{
printf("file open error!\n");
return -1;
}
fscanf(in,"%d%d%d",&N,&B,&D);
end=pow(2,B);
set[0]=0; //0一定在集合中
j=1;
for(start=1;start<end&&j<N;start++) //从小到大一次枚举加入合适的数
{
if(check(start,j))
{
set[j]=start;
j++;
}
}
for(i=0;i<N;i++) //按照要求输出,注意十个换行,最后一个需要换行
{
if(i%10==9||i==N-1)
fprintf(out,"%d\n",set[i]);
else
fprintf(out,"%d ",set[i]);
}
return 0;
}