USACO Section 2.1 Hamming Codes (dfs)

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

题意:输入N,B,D 表示,在 [0,2^B-1] 中找出最小的 N 个数,两两间的 hamming 距离大于等于 D。
分析:从 0 开始依次搜索下去,找到前 N 就输入。这么暴力居然也过了 = =!!
View Code
 1 /*
 2   ID: dizzy_l1
 3   LANG: C++
 4   TASK: hamming
 5 */
 6 #include<iostream>
 7 #include<cmath>
 8 #include<cstdio>
 9 
10 using namespace std;
11 
12 int MAXN,N,B,D,ans[70];
13 bool flag;
14 
15 bool judge(int a,int cnt)
16 {
17     int i,j,t,tt,c;
18     for(i=0;i<cnt;i++)
19     {
20         c=0;
21         t=ans[i]^a;
22         for(j=0;j<B;j++)
23         {
24             tt=pow(2,j);
25             if(tt&t) c++;
26         }
27         if(c<D) return false;
28     }
29     return true;
30 }
31 
32 void dfs(int a,int cnt)
33 {
34     int i;
35     if(flag||cnt>MAXN+1) return ;
36     if(MAXN-a+1<N-cnt) return  ;
37     if(cnt==N)
38     {
39         for(i=0;i<N-1;i++)
40         {
41             if((i+1)%10==0)
42                 printf("%d\n",ans[i]);
43             else
44                 printf("%d ",ans[i]);
45         }
46         printf("%d\n",ans[i]);
47         flag=true;
48         return ;
49     }
50     for(i=a;i<=MAXN;i++)
51     {
52         if(judge(i,cnt))
53         {
54             ans[cnt]=i;
55             dfs(i+1,cnt+1);
56         }
57     }
58 }
59 
60 int main()
61 {
62     freopen("hamming.in","r",stdin);
63     freopen("hamming.out","w",stdout);
64     int cnt;
65     while(scanf("%d %d %d",&N,&B,&D)==3)
66     {
67         MAXN=pow(2,B)-1;
68         flag=false;cnt=0;
69         ans[cnt++]=0;
70         dfs(1,cnt);
71     }
72     return 0;
73 }

 



posted @ 2012-08-30 18:46  mtry  阅读(490)  评论(0)    收藏  举报