当前位置: 首页 > 工具软件 > ANMS-Codes > 使用案例 >

USACO——Hamming Codes

田巴英
2023-12-01

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
思路:从零开始,两两异或,如果异或后二进制数中1的个数大于D即输出


/*
ID: youqihe1
PROG: hamming
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>

using namespace std;
int cal(int n)
{
     unsigned int c =0 ;
    for (c =0; n; ++c)
    {
        n &= (n -1) ; // 清除最低位的1
    }
    return c ;

}
int A[100];
int s=1;
int pow(int a,int n)
{
    if(!n)
        return 1;
    int b=a;
    while(--n)
        a*=b;
    return a;
}
int main() {
    FILE *fin  = fopen ("hamming.in", "r");
    FILE *fout = fopen ("hamming.out", "w");
    int N,B,D;
    fscanf(fin,"%d %d %d",&N,&B,&D);
    int i,j,k,n=pow(2,B)-1;
    A[0]=0;
    while(s<N)
    {

        for(i=A[s]+1;i<=n;i++)
        {
            int flag=1;
            for(j=0;j<s;j++)
            {
                int a=A[j]^i;
                if(cal(a)<D)
                {
                    flag=0;
                    break;
                }
            }
            if(flag)
            {
                A[s++]=i;
                break;
            }
        }
    }
    k=0;
    for(i=0;i<s/10;i++)
    {
        for(j=0;j<9;j++)
            fprintf(fout,"%d ",A[k++]);
        fprintf(fout,"%d\n",A[k++]);
    }
    for(i=0;i<s%10-1;i++)
        fprintf(fout,"%d ",A[k++]);
    if(s%10) fprintf(fout,"%d\n",A[k]);
    return 0;
}






 类似资料:

相关阅读

相关文章

相关问答