USACO 2.1 Hamming Codes

来源:互联网 发布:js 设置css 编辑:程序博客网 时间:2024/05/01 10:23

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 0100Bit 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 7682 85 97 102 120 127


题目要求给出n个 b位二进制串对应的十进制数字,使得这n个数相互之间的海明距离不小于d。

这道题目就是直接枚举所有b位的二进制串,然后将符合要求的输出。可以用深搜,有下面两个tricky的地方要注意:

(1)枚举第k位时,先置为1再置为0,这样搜索能保证最后输出的数字都是按序排列的。

(2)计算海明距离时,将两数各位异或值相加即可。(total = a1^c1+a2^c2+……+ab^cb)


我做这道题倒是一遍写出来了,但是因为没看清题目是≥d而不是=d,检查了半天的错误,无语。。。还有他的输出要求格式也稍微得注意一下。。。

代码如下:

/*ID: gjj50201LANG: C++TASK: hamming*/#include <stdio.h>#include <iostream>#include <stdlib.h>#include <algorithm>using namespace std;int n,b,d;int num[8];int ans[64][8];int cnt;int dist(int *a, int *c){int total = 0;for(int i=0;i<b;i++)total += a[i]^c[i];return total;}int solve(int *a){int sum = 0;for(int i = 0; i<b; i++)sum = sum*2 + a[i];return sum;}int check(){for(int i=0;i<cnt;i++){if(dist(ans[i], num) < d)return 0;}return 1;}void dfs(int k){if(cnt >= n)return;if(k >= b){if(check()){cout<<solve(num);if( (cnt+1) % 10 == 0)cout<<endl;else if(cnt < n-1)cout<<" ";elsecout<<endl;for(int i=0;i<b;i++)ans[cnt][i] = num[i];cnt++;}return;}num[k] = 0;dfs(k+1);num[k] = 1;dfs(k+1);}int main(){freopen("hamming.in","r",stdin);freopen("hamming.out","w",stdout);cin>>n>>b>>d;cnt = 0;dfs(0);return 0;}


0 0
原创粉丝点击