You are viewing a single comment's thread. Return to all comments →
My C++ Code,passes all test cases
#include <bits/stdc++.h> using namespace std; vector<int> p; vector<int> ranks; vector<int> num; int N; void init(){ for(int i=0;i<=N;i++){ p.push_back(i); ranks.push_back(0); num.push_back(1); } } int find(int z){ if(p[z]!=z) p[z]=find(p[z]); return (p[z]); } void join(int x,int y){ int x1=find(x); int y1=find(y); if(x1==y1) return; else{ int t1=ranks[x1]; int t2=ranks[y1]; if(t1==t2){ p[x1]=y1; ranks[y1]++; num[y1]=num[y1]+num[x1]; num[x1]=num[y1]; } else if(t1<t2){ p[x1]=y1; num[y1]=num[y1]+num[x1]; num[x1]=num[y1]; } else{ p[y1]=x1; num[x1]=num[x1]+num[y1]; num[y1]=num[x1]; } } } int numb(int k){ int p=find(k); return num[p]; } int main() { int q; cin>>N>>q; init(); while(q--){ char c; cin>>c; if(c=='M'){ int x,y; cin>>x>>y; join(x,y); } else{ int z; cin>>z; cout<<numb(z)<<endl; } } return 0; }
Seems like cookies are disabled on this browser, please enable them to open this website
Merging Communities
You are viewing a single comment's thread. Return to all comments →
My C++ Code,passes all test cases