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