Codeforce 468B Two Sets

本文介绍了一个关于将一组不重复整数划分到两个不同集合的问题,并提供了一种贪心算法解决方案。该问题要求若某个数属于某集合,则其补数也必须属于同一集合。文章通过排序和使用哈希表来实现这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

B. Two Sets
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied:

  • If number x belongs to set A, then number a - x must also belong to set A.
  • If number x belongs to set B, then number b - x must also belong to set B.

Help Little X divide the numbers into two sets or determine that it's impossible.

Input

The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109).

Output

If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B.

If it's impossible, print "NO" (without the quotes).

Sample test(s)
input
4 5 9
2 3 4 5
output
YES
0 0 1 1
input
3 3 4
1 2 4
output
NO



在此讲出此题的贪心做法,不过我并不会证明,我只看到了题中有个条件说每个数字不一样,我就想会不会有贪心做法,就贪心交了一发,先排序数列,从最小的数字开始,看是否能加入数字大的集合,能加入,这个数字和max(a,b)-这个数字都要置false,然后在判断能否加入小的集合,不然就直接判NO。中间过程全用map完成。


代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<string>
#include<cstring>
#include<algorithm>
#include<fstream>
#include<queue>
#include<map>
#include<stack> 
#include<vector>
#include<cmath>
#include<iomanip>
#define rep(i,n) for(i=1;i<=n;i++)
#define MM(a,t) memset(a,t,sizeof(a))
#define INF 1e9
typedef long long ll;
#define mod 1000000007
using namespace std;
int n,b[10],ii;
int a[100020];
int res[100020];
map<int,bool> g;
map<int,int> index;
bool ff;
int main()
{
	int i,j;
    
    while(scanf("%d%d%d",&n,&b[0],&b[1])!=EOF){
      ff=true;
	  g.clear(); index.clear();
	  if(b[0]>b[1]) ii=0;
	  else          ii=1;
	  rep(i,n){
	  	int tmp;
		scanf("%d",&tmp);
		a[i]=tmp;
		g[tmp]=true;
		index[tmp]=i;
	  }
  	  sort(a+1,a+n+1);
  	  rep(i,n)
  	  if(g[a[i]])
	  {
  	    int t1=a[i],t2=b[ii]-t1,t3=b[1-ii]-t1;
		if(g[t2]){
		  res[index[t1]]=ii;
		  res[index[t2]]=ii;
		  g[t1]=false; g[t2]=false;	
		}	
		else if(g[t3]){
			   res[index[t1]]=1-ii;
			   res[index[t3]]=1-ii;
			   g[t1]=false;
			   g[t3]=false;
     		 }
     		 else{
 		     	ff=false;
 		     	break;
 		     }
  	  }
  	  if(ff){
  	    printf("YES\n");
		rep(i,n-1) printf("%d ",res[i]);
		printf("%d\n",res[n]);	
  	  }
  	  else printf("NO\n");
    }
    
	
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值