UVa 729 - The Hamming Distance Problem 排列组合

 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  H from 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 


This number can be very large. The program should work for .

Print a blank line between datasets.

Sample Input 

1

4 2

Sample Output 

0011
0101
0110
1001
1010
1100


Miguel Revilla 
2000-08-31

题意:

給2個相同長度的2元字串,比較他們在相同位置的內容,並計算各位置內容不一樣的總數,我們稱該數為它們之間的Hamming distance。這任務可以經由對字串中各相同位置字元作XOR的運算或者做2進位的相加(但不進位)而得到。以下的例子為2個長度為10的2元字串A、B經過XOR運算。可以看出共有6個1,所以其Hamming distance為6。

                               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

你的任務是給你字串的長度(N)及所要求的Hamming distance(H),請你輸出所有這樣的2元字串,也就是長度為N的二元字串,且恰好有H個1的字串。由數學我們得知這樣的字串共有C(N,H)個。也就是:

    N!
─────
(N-H)! H!

Input

輸入的第一列有一個正整數,代表以下有多少組測試資料。

每組測試資料一列,含有2個正整數N、H(1 <= H <= N <= 16)。N代表字串的長度,H代表Hamming distance。

請參考Sample Input。

Output

對每一組測試資料,輸出所有長度為N,且Hamming distance為H的二元字串,並由小到大輸出。測試資料間請空一列。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAX=100;

char data[MAX];
int n, h;

int main()
{
//	freopen("in.txt","r",stdin);
	int nCase;
	cin >> nCase;
	for(int j=1; j <= nCase; j++)
	{
		memset(data, '\0', sizeof(data));
		cin >> n>>h;
		for(int i=n-1; i >=0; i--)
		{
			if(h)
			{
				data[i]='1';
				h--;
			}else
				data[i]='0';
		}
		do{
			cout << data << endl;
		}while(next_permutation(data, data+strlen(data)));
		// WA了两次 评测系统就卡这个空行  
		if(j!=nCase)cout << endl;
	}
	return 0;
} 


你可能感兴趣的:(C++,算法,uva)