CodeForce731-C. Socks-并查集
http://codeforces.com/contest/731/problem/C
并查集水题
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #define maxn 222222 5 using namespace std; 6 int color[maxn],fa[maxn]; 7 int index[maxn]; 8 int fin(int x) { 9 if (x==fa[x]) 10 return x; 11 return fa[x]=fin(fa[x]); 12 } 13 void unio(int a, int b) { 14 fa[fin(a)]=fin(b); 15 } 16 bool com(int x,int y) 17 { 18 if (fin(x)==fin(y)) return color[x] > color[y]; 19 else return fin(x)>fin(y); 20 } 21 int main() 22 { 23 //freopen("in.txt","r",stdin); 24 int N,M,K; 25 scanf("%d%d%d",&N,&M,&K); 26 for (int i = 1 ; i <= N; i++ ) 27 { 28 int t; 29 scanf("%d",&t); 30 index[i] = i; 31 color[i] = t; 32 fa[i] = i; 33 } 34 for (int i = 1; i <= M; i++) 35 { 36 int a,b; 37 scanf("%d%d",&a,&b); 38 if (fin(a)!=fin(b)) unio(a,b); 39 } 40 sort(index+1,index+N+1,com); 41 int ans = 0; 42 for (int i = 1; i<= N; ) 43 { 44 int tfa = fin(index[i]); 45 int ma = 0; 46 int s = i; 47 while (i<=N && tfa == fin(index[i])) 48 { 49 int tma = 0; 50 int tc = color[index[i]]; 51 while (i<=N && color[index[i]] == tc && tfa == fin(index[i]) ) 52 { 53 tma++; 54 i++; 55 } 56 ma = max(ma,tma); 57 } 58 ans+=( (i-s) - ma ); 59 } 60 cout << ans << endl; 61 return 0; 62 }