Two Sets CodeForces - 468B
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).
Example
4 5 9
2 3 4 5
YES
0 0 1 1
3 3 4
1 2 4
NO
Note
It's OK if all the numbers are in the same set, and the other one is empty.
增加一个案列:
4 10 16
4 6 10 12
题解:哇,被坑惨了。用二分搜索调了好久才发现有些情况解决不了,比如a-x和b-x同时存在时,不能直接确定放在那个位置。后面看了
别人的题解(http://www.cnblogs.com/zhien-aa/p/6726862.html),才知道用并查集管理。
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 const int maxn=1e5+5; 5 6 int n,a,b; 7 int F[maxn],num[maxn]; 8 9 int Find(int x){ 10 if(x==F[x]) return F[x]; 11 return F[x]=Find(F[x]); 12 } 13 14 int main() 15 { while(cin>>n>>a>>b){ 16 map<int,int> p; 17 for(int i=1;i<=n+2;i++) F[i]=i; 18 for(int i=1;i<=n;i++){ 19 cin>>num[i]; 20 p[num[i]]=i; 21 } 22 int temp; 23 for(int i=1;i<=n;i++){ 24 temp=Find(i); 25 if(p[a-num[i]]) F[temp]=Find(p[a-num[i]]); 26 else F[temp]=Find(n+1); 27 temp=Find(i); 28 if(p[b-num[i]]) F[temp]=Find(p[b-num[i]]); 29 else F[temp]=Find(n+2); 30 } 31 if(Find(n+1)==Find(n+2)) cout<<"NO"<<endl; 32 else{ 33 cout<<"YES"<<endl; 34 for(int i=1;i<=n;i++) printf("%d%c",Find(i)==Find(n+1),i==n?'\n':' '); 35 } 36 } 37 }