天天看點

USACO SECTION 2.1 Hamming Codes

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
      
#include<stdlib.h>
#include<string.h>

int CodeWords[64];
int WordsNumber,Length,Distance;

int IsTrue(int i,int NextWords)
{
	int j,k;
	int a,b,count;
	for(j=0;j<i;j++)
	{
		a=CodeWords[j];
		b=NextWords;
		count=0;
		for(k=0;k<Length;k++)
		{
			if((a&1)!=(b&1))
				count++;
			a>>=1;
			b>>=1;
		}
		if(count<Distance)
			return 0;
	}
	return 1;
}

int main()
{
	FILE *fin,*fout;
	fin=fopen("hamming.in","r");
	fout=fopen("hamming.out","w");
	
	fscanf(fin,"%d %d %d",&WordsNumber,&Length,&Distance);
	
	int i,j,k;
	int NextWord;
	
	CodeWords[0]=0;
	for(i=1;i<WordsNumber;i++)
	{
		NextWord=CodeWords[i-1]+1;
		while(!IsTrue(i,NextWord))
		{
			NextWord++;
		}	
		CodeWords[i]=NextWord;
	}
	
	for(i=0;i<WordsNumber;i++)
	{
		fprintf(fout,"%d",CodeWords[i]);
		if((i+1)%10==0)
			fprintf(fout,"\n");
		else
		if(i!=WordsNumber-1)
			fprintf(fout," ");
	}
	if(i%10!=0)
		fprintf(fout,"\n");
	
	return 0;
}
           

感覺題好水。。沒有以前花好長時間做出來的那種喜悅的感覺了= =|||

多去NOCOW上面看看别人的做法。看看能不能多點收獲