usaco:2.1.5 Hamming Codes Hamming code
I. Description of the topic
★hamming Codes Hamming code gives n,b and D: Find N codes (1 <= n <= 64), each encoded with a B bit (1 <= B <= 8), so that the 22 encoding has at least the "Hamming distance" of D units (1 <= D <= 7). " Hamming distance "refers to the number of different bits in binary notation for two encodings. See the difference between the following two encodings 0x554 and 0x234 (0x554 represents a hexadecimal number, each bit is 5,5,4):
0x554 = 0101 0101 0100
0x234 = 0010 0011 0100
Different bits: XXX xx
Since there are five bits different, "Hamming distance" is 5.
Program name:hamming
INPUT FORMAT
One row, including N, B, D.
SAMPLE INPUT (file hamming.in)
16 7 3
OUTPUT FORMAT
N encodings (in decimal notation), to sort, 10 rows. If there is more than one solution, your program will output such a solution: if it
As the number of 2^b, its value should be minimal.
SAMPLE OUTPUT (file Hamming.out)
0 7 25 30 42 45 51 52 75 76
82 85 97 102 120 127
second, the idea of solving problems
This topic is very simple, direct traversal can be. But to figure out what you need, see test instructions. First of all, we should make it clear that 0 must be in this N code, with the traversal starting point.
We can traverse the 1 to the largest B-bit binary number, and then compare the current number to the number of n found to meet the D distance requirement until we find n encoding.
Of course, there will be some differences in the implementation, 1. Whether the preprocessing finds the distance between all B-digits; 2. Two number distance calculation, you can either direct XOR or the number of 1 in the result, or bitwise comparison of the corresponding bit is the same.
Source
#include <iostream>
#include <cstdio>
using namespace std;
int n,b,d;
int num[256+10];
int cout_num (int a) {//calculates the distance between B-digits and 0, that is, the number of 1 in the B-digit
int i,cnt=0;
for (i=0;i<b;i++)
{ cnt=cnt+ (a&1);
a=a>>1;
}
return cnt;
}
int isOK (int x,int c,int d) {
int i,temp;
for (i=0;i<c;i++)
{
temp=x^num[i];//xor result, you can calculate the number of B digits x by 1
if (cout_num (temp) <d)
return 0 ;
}
return 1;
}
int main ()
{
freopen ("hamming.in", "R", stdin);
Freopen ("Hamming.out", "w", stdout);
scanf ("%d%d%d", &n,&b,&d);
num[0]=0; 0 is bound to arise.
int vis=0;
int i,j;
for (i=1;i<=256;i++)
{
if (isOK (i,vis+1,d))
num[++vis]=i;
}
i=0;
for (i=0;i<n;i++) {
printf ("%d", Num[i]);
if ((i+1)%10==0 | | i==n-1)
cout<<endl;
else if (i<n-1)
printf ("");//cout<< "; Do not know how to use cout output space
}
return 0;
}
Because it is a beginner, the programming ability is limited, does not reach the level of professional programmers, may mislead everyone, please read it, the text editing is also general, the text may have inappropriate wording. Blog post the mistakes and shortcomings of the reader, please criticize.