We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicclassSolution{publicstaticintfind(intv,int[]parent){if(v==parent[v-1]){returnv;}parent[v-1]=find(parent[v-1],parent);returnparent[v-1];}publicstaticvoidunion(inta,intb,int[]parent,int[]st){intca=find(a,parent);intcb=find(b,parent);if(ca==cb){return;}st[cb-1]=st[ca-1]+st[cb-1];parent[ca-1]=cb;}publicstaticvoidmain(String[]args)throwsIOException{/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */BufferedReaderrd=newBufferedReader(newInputStreamReader(System.in));;BufferedWriterwt=newBufferedWriter(newPrintWriter(System.out));String[]ins=rd.readLine().split(" ");intn=Integer.parseInt(ins[0]);intq=Integer.parseInt(ins[1]);int[]parent=newint[n+1];int[]st=newint[n+1];for(inti=0;i<n;i++){parent[i]=i+1;st[i]=1;}for(intk=0;k<q;k++){String[]in=rd.readLine().split(" ");switch(in[0]){case"M":inti=Integer.parseInt(in[1]);intj=Integer.parseInt(in[2]);union(i,j,parent,st);break;case"Q":i=Integer.parseInt(in[1]);intp=find(i,parent);intcount=st[p-1];wt.write(count+"\n");break;}}wt.flush();wt.close();rd.close();}}
Cookie support is required to access HackerRank
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 →
Java Solution: