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
If it‘s impossible, print "NO" (without the quotes).
Example
Input4 5 9Output
2 3 4 5
YESInput
0 0 1 1
3 3 4Output
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 }
Two Sets CodeForces - 468B