23dfcca431 2011-02-23 kinaba: //------------------------------------------------------------- 23dfcca431 2011-02-23 kinaba: // Union-Find 23dfcca431 2011-02-23 kinaba: // Balancing + Path-Compression : O(invAckermann) 23dfcca431 2011-02-23 kinaba: // 23dfcca431 2011-02-23 kinaba: // Verified by 23dfcca431 2011-02-23 kinaba: // - SRM Member Pilot 2 Div1 LV2 23dfcca431 2011-02-23 kinaba: //------------------------------------------------------------- 23dfcca431 2011-02-23 kinaba: 23dfcca431 2011-02-23 kinaba: struct UnionFind 23dfcca431 2011-02-23 kinaba: { 23dfcca431 2011-02-23 kinaba: vector<int> uf, sz; 23dfcca431 2011-02-23 kinaba: int nc; 23dfcca431 2011-02-23 kinaba: 23dfcca431 2011-02-23 kinaba: UnionFind(int N): uf(N), sz(N,1), nc(N) 23dfcca431 2011-02-23 kinaba: { for(int i=0; i<N; ++i) uf[i] = i; } 23dfcca431 2011-02-23 kinaba: int size() 23dfcca431 2011-02-23 kinaba: { return nc; } 23dfcca431 2011-02-23 kinaba: int Find(int a) 23dfcca431 2011-02-23 kinaba: { return uf[a]==a ? a : uf[a]=Find(uf[a]); } 23dfcca431 2011-02-23 kinaba: bool Union(int a, int b) 23dfcca431 2011-02-23 kinaba: { 23dfcca431 2011-02-23 kinaba: a = Find(a); 23dfcca431 2011-02-23 kinaba: b = Find(b); 23dfcca431 2011-02-23 kinaba: if( a != b ) 23dfcca431 2011-02-23 kinaba: { 23dfcca431 2011-02-23 kinaba: if( sz[a] >= sz[b] ) swap(a, b); 23dfcca431 2011-02-23 kinaba: uf[a] = b; 23dfcca431 2011-02-23 kinaba: sz[b] += sz[a]; 23dfcca431 2011-02-23 kinaba: --nc; 23dfcca431 2011-02-23 kinaba: } 23dfcca431 2011-02-23 kinaba: return (a!=b); 23dfcca431 2011-02-23 kinaba: } 23dfcca431 2011-02-23 kinaba: };