`
Jianquan
  • 浏览: 18896 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

UVa 729 The Hamming Distance Problem

    博客分类:
  • UVa
阅读更多
题目:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=670
枚举十进制数0~2^N-1,对于每一个数都跟0异或,并把异或的结果转换成二进制,计算二进制数中1的个数,如果等于H,那么把该二进制数输出,注意不要忽略了前导零。
#include<stdio.h>
#include<math.h>
void solve(int XOR,int N,int H)
{
	int res[20],top=0,cnt=0;
	while(XOR>0)
	{
		int tmp=XOR%2;
		if(tmp) cnt++;
		res[++top]=tmp;
		XOR/=2;
	}
	if(cnt==H)
	{
		if(top<N)
		{
			int t=N-top;
			while(t--) putchar('0');
		}
		while(top)
		{
			printf("%d",res[top]);
			top--;
		}
		putchar('\n');
	}
}
int main()
{
	int i,lim,XOR,T,N,H;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&N,&H);
		lim=pow(2,N);
		for(i=0;i<lim;i++)
		{
			XOR=i^0;
			solve(XOR,N,H);
		}
		if(T>0) putchar('\n');
	}
	return 0;
}

PS:今天才发现,UVa会把格式错误看作是Wrong Answer,不知道是不是所有题目都是这样。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics