uva 729 - The Hamming Distance Problem

本文介绍了汉明距离的概念及其计算方法,并提供了一种通过XOR运算来找出两个10位字符串之间的汉明距离的示例。同时,文章还讨论了如何生成所有与全0字符串具有特定汉明距离的字符串,并给出了相应的C语言实现代码。

The Hamming Distance Problem 

The Hamming distance between two strings of bits (binary integers) is the number of corresponding bit positions that differ. This can be found by using XOR on corresponding bits or equivalently, by adding corresponding bits (base 2) without a carry. For example, in the two bit strings that follow:

                               A      0 1 0 0 1 0 1 0 0 0
                               B      1 1 0 1 0 1 0 1 0 0
                            A XOR B = 1 0 0 1 1 1 1 1 0 0

The Hamming distance (H) between these 10-bit strings is 6, the number of 1's in the XOR string.

Input 

Input consists of several datasets. The first line of the input contains the number of datasets, and it's followed by a blank line. Each dataset contains N, the length of the bit strings and H, the Hamming distance, on the same line. There is a blank line between test cases.

Output 

For each dataset print a list of all possible bit strings of length N that are Hamming distance Hfrom the bit string containing all 0's (origin). That is, all bit strings of length N with exactly H 1's printed in ascending lexicographical order.


The number of such bit strings is equal to the combinatorial symbol C(N,H). This is the number of possible combinations of N-H zeros and H ones. It is equal to 

\begin{displaymath}{N!} \over {(N-H)! H!}\end{displaymath}

This number can be very large. The program should work for $1 \le H \le N\le 16$.

Print a blank line between datasets.

Sample Input 

1

4 2

Sample Output 

0011
0101
0110
1001
1010
1100

方法 :确定遍历上限和下限。

代码 :
#include 
#define N 17
int num_one(int n)
{
    int num;
    num = 0;
    while(n){
	num++;
	n = (n-1) & n;
    }
    return num;
}
char* atob(char str[], int inter, int n)
{
    int i, t;
    for(i = 0; i < n; i++)
	str[i] = '0';
    str[n] = '\0';
    t = 1;
    for(i = 0; i < n; i++){
	if(inter&t){
	    str[n-i-1] = '1';
	}
	t <<= 1;
    }
    return str;
}
int main()
{
    char str[N];
    int n, h, i, inter, t, low, up;
    scanf("%d", &t);
    while(t-- > 0){
        scanf("%d %d", &n, &h);
        low = 1;
        up = 1;
        for(i = 0; i < h; i++)
            low <<= 1;
        low--;
        for(i = 0; i < n; i++)
            up <<= 1;
        up--;
        for(inter = low; inter <= up; inter++){
            if(num_one(inter) == h)
                printf("%s\n", atob(str, inter, n));
        }
        if(t)
            printf("\n");
    }
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值