HackerEarth: City and Campers 2 (DSU-UnionFind)


HackerEarth: City and Campers 2 (DSU-UnionFind)


///==================================================///
/// HELLO WORLD !! ///
/// IT'S ME ///
/// BISHAL GAUTAM ///
/// [ bsal.gautam16@gmail.com ] ///
///==================================================///
#include<bits/stdc++.h>
#define X first
#define Y second
#define mpp make_pair
#define nl printf("\n")
#define SZ(x) (int)(x.size())
#define pb(x) push_back(x)
#define pii pair<int,int>
#define pll pair<ll,ll>
///---------------------
#define S(a) scanf("%d",&a)
#define P(a) printf("%d",a)
#define SL(a) scanf("%lld",&a)
#define S2(a,b) scanf("%d%d",&a,&b)
#define SL2(a,b) scanf("%lld%lld",&a,&b)
///------------------------------------
#define all(v) v.begin(),v.end()
#define CLR(a) memset(a,0,sizeof(a))
#define SET(a) memset(a,-1,sizeof(a))
#define fr(i,a,n) for(int i=a;i<=n;i++)
#define UNIK(v) sort(all(v)),v.resize( unique(all(v)) -v.begin() );
using namespace std;
typedef long long ll;
///==========CONSTANTS=============///
/// Digit 0123456789012345678 ///
#define MX 100005
#define inf 1000000010
#define MD 1000000007LL
#define eps 1e-9
///===============================///

int par[MX+2];
int GP(int x) {
if( x==par[x] ) return x;
return ( par[x]=GP( par[x] ) );
}

int Sz[MX+2];
int Fr[MX+2];
set<int>St;
int main() {
int n,m;
S2(n,m);
fr(i,1,n)par[i]=i,Sz[i]=1,Fr[1]++;
St.insert(1);
int ans=0;
while(m--) {
int x,y;
S2(x,y);
/// output the min diff betwn any two groups
int xx=GP(x);
int yy=GP(y);
if(xx!=yy) {
par[xx]=yy;

int sy=Sz[yy];
Fr[ sy ]--;
if( Fr[sy]==0 ) St.erase( sy );

int sx=Sz[xx];
Fr[ sx ]--;
if( Fr[sx]==0 ) St.erase( sx );

Sz[ yy ]+=Sz[ xx ];
sy=Sz[ yy ];
Fr[ sy ]++;
if( Fr[sy]==1 ) St.insert( sy );

int pv=-1;
int mn=n+1;
for(set<int>:: iterator it=St.begin(); it!=St.end(); it++) {
///Coz, there will be no more than Sqrt different groups
int vl=(*it);
if( Fr[ vl ]>1 ) { /// More than one siz-val then diff 0.
mn=0;
break;
}
if( pv!=-1 ) {
mn=min(mn,vl-pv);
}
pv=vl;
}
if(mn==n+1)mn=0;///If single group formed
ans=mn;
}
printf("%d\n",ans);
}

return 0;
}

Comments

Popular posts from this blog

Two Pointers Technique & Binary Search For Beginners

Problem : Codeforces Round #406 (Div. 1) B [ Legacy ]( Dijakstra, Segment tree)