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; } d52cf3ca74 2012-12-12 kinaba: int size(int a) d52cf3ca74 2012-12-12 kinaba: { return sz[Find(a)]; } 23dfcca431 2011-02-23 kinaba: int Find(int a) 23dfcca431 2011-02-23 kinaba: { return uf[a]==a ? a : uf[a]=Find(uf[a]); } da169a2bbe 2015-06-06 kinaba: // Semi-compression w.o. recursion. da169a2bbe 2015-06-06 kinaba: //{ while(uf[a] != a) a=uf[a]=uf[uf[a]]; return 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: };