USACO 2.1 Hamming Codes

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位二進制串對應的十進制數字,使得這n個數相互之間的海明距離不小於d。

這道題目就是直接枚舉所有b位的二進制串,然後將符合要求的輸出。可以用深搜,有下面兩個tricky的地方要注意:

(1)枚舉第k位時,先置爲1再置爲0,這樣搜索能保證最後輸出的數字都是按序排列的。

(2)計算海明距離時,將兩數各位異或值相加即可。(total = a1^c1+a2^c2+……+ab^cb)


我做這道題倒是一遍寫出來了,但是因爲沒看清題目是≥d而不是=d,檢查了半天的錯誤,無語。。。還有他的輸出要求格式也稍微得注意一下。。。

代碼如下:

/*
ID: gjj50201
LANG: 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<<" ";
			else
				cout<<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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章