uva 729 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
N!/((N − H)!H!)
This number can be very large. The program should work for 1 ≤ H ≤ N ≤ 16.

Sample Input
1
4 2
Sample Output
0011
0101
0110
1001
1010
1100

中文:

給你一個只包含0和1的字符串,長度爲n,現在要去這個字符串裏面有h個1.
問你有多少種排列方式

從小到大輸出

代碼:

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
const int maxn=20;
char s[maxn],ans[maxn];
int n,h;

void permutation(int n,char *p,char *a,int cur)
{
    if(cur==n)
    {
        for(int i=0;i<n;i++)
            cout<<a[i];
        cout<<endl;
    }
    else
    {
        for(int i=0;i<n;i++)
        {
            if(!i||p[i]!=p[i-1])
            {
                int c1=0,c2=0;
                for(int j=0;j<cur;j++)
                    if(p[i]==a[j])
                    c1++;
                for(int j=0;j<n;j++)
                    if(p[i]==p[j])
                    c2++;
                if(c1<c2)
                {
                    a[cur]=p[i];
                    permutation(n,p,a,cur+1);
                }
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>h;
        memset(s,'0',sizeof(s));
        for(int i=n-1,j=h;j>0;i--,j--)
            s[i]='1';
        permutation(n,s,ans,0);
        if(t)
            cout<<endl;
    }
    return 0;
}




解答:

用小白書上的生成排列模板就可以了

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