1. 程式人生 > >codeforces 468B two set(並查集)

codeforces 468B two set(並查集)

include main ace code fin pre c++ color ret

codeforces 468B two set(並查集)
n+1 表示 B 組
n+2 表示 A 組

按照 這題的做法
應該是 如果 滿足 num[ i ] a-num[ i ] 則他們同一組 但不一定 就一定是 都是 A 組
也可能都是 B 組 然而如果不滿足這個條件的話,就直接加入 B組
然後如果滿足 num[ i ] b-num[ i ] 則加入同一組 然後不滿足就 加入 A 組

 1 #include <bits/stdc++.h> 
 2 using namespace std ; 
 3 
 4 const int maxn = 1e5+11
; 5 int n,a,b ; 6 int num[maxn],fa[maxn] ; 7 8 inline int find(int x) 9 { 10 if(fa[x] == x) return x ; 11 return fa[x] = find(fa[x]) ; 12 } 13 14 int main() 15 { 16 scanf("%d%d%d",&n,&a,&b) ; 17 map<int,int> mp ; 18 for(int i=1;i<=n;i++) 19 scanf("
%d",&num[ i ]) , mp[ num[ i ] ] = i ; 20 21 int x ; 22 for(int i=1;i<=n+2;i++) fa[ i ] = i ; 23 for(int i=1;i<=n;i++) 24 { 25 x = find( i ) ; 26 if( mp.count( a-num[ i ] ) ) 27 fa[ x ] = find( mp[ a-num[ i ] ] ) ; 28 else 29
fa[ x ] = find( n+1 ) ; // 不行的話就加入B 組 30 x = find( i ) ; 31 if( mp.count( b-num[ i ] ) ) 32 fa[ x ] = find( mp[ b-num[ i ] ] ) ; 33 else 34 fa[ x ] = find( n+2 ) ; 35 } 36 if( find(n+1)==find(n+2) ) 37 { 38 printf("NO\n") ; 39 return 0 ; 40 } 41 printf("YES\n") ; 42 for(int i=1;i<=n;i++) 43 printf("%d ",find( i )==find(n+1) ) ; 44 45 return 0 ; 46 }

codeforces 468B two set(並查集)