51nod1315(二进制)

对于一个数,如果X的二进制位为0而它的该位为1,那么这个数可以就可以不删除,把这类数筛选出来

然后就是统计剩下的数中,每个对应X位为1同时有多少个数该位也为1,最少的那个的个数就是答案,因为只要

把这一位的1全破坏掉,就无论如何不会组合出X了

#include<cstdio> 
#include<algorithm>
using namespace std;
const int N = 50+4;
int a[N],X;
int b[50];
bool vis[N];
int sum[50];
int main()
{
	int n;
	scanf("%d%d",&n,&X);
	for(int i = 0; i<n; i++)
		scanf("%d",&a[i]);
	int cnt = 0;
	while(X)
	{
		if(X&1) b[cnt++] = 1;
		else cnt++;
		X>>=1;
	}
	for(int i = 0; i<n; i++){
		int t = a[i]; int pos = 0;
		while(t)
		{
			if((t&1)&&(b[pos]==0)) {vis[i]=true ;break;}
			pos++;
			t>>=1;
		}
	}
	for(int i = 0; i<n; i++)
		if(!vis[i]) {
			int t = a[i]; int pos = 0;
			while(t)
			{
				if((t&1)&&b[pos]==1) {
					sum[pos]++;
					pos++;
				}
				else{
					pos++;
				}
				t>>=1;
			}
		}
	int ans = 60;
	for(int i = 0; i<cnt; i++){
	if(b[i]==1)	ans = min(ans,sum[i]);
	}
	printf("%d\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41156122/article/details/81668825