uva 729 - The Hamming Distance Problem 枚举排列

参考《算法竞赛入门经典》,用递归枚举时。枚举排列时,到cur==n,即够n个元素的时候,才终止递归。枚举子集,则枚举到0-n个元素都要进行操作。


一:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int maxn=20;
int P[]={0,1};
int A[maxn];

void print_permutation(int n,int h,int *A,int *P,int cur)
{
	int i;
	if(cur==n)
	{
		for(i=0;i<n;i++)  printf("%d",A[i]);
		printf("\n");
	}
	else  for(i=0;i<2;i++)
	{
		int c=0;
		for(int j=0;j<cur;j++) if(A[j]==P[i]) c++;
		if(P[i] && c<h || !P[i] && c<n-h)
		{
			A[cur]=P[i];
			print_permutation(n,h,A,P,cur+1);
		}
	}
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("729.txt","r",stdin);
#endif
	int N;
	scanf("%d",&N);
	while(N--)
	{
		int n,h;
		scanf("%d%d",&n,&h);
		print_permutation(n,h,A,P,0);
		if(N) printf("\n");
	}
    return 0;
}


二:
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=20;
int A[maxn];

int main()
{
#ifndef ONLINE_JUDGE
    freopen("729.txt","r",stdin);
#endif
	int N;
	scanf("%d",&N);
	while(N--)
	{
		int n,h;
		scanf("%d%d",&n,&h);
		int i;
		for(i=0;i<n-h;i++) A[i]=0;
		for(;i<n;i++) A[i]=1;
		do
		{
			for(i=0;i<n;i++) printf("%d",A[i]);
			printf("\n");
		}while(next_permutation(A,A+n));
		if(N) printf("\n");
	}
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值