1 条题解
-
0
JAVA AC代码(并查集):
import java.util.*; import java.util.StringTokenizer; import java.io.*; public class Main { static int fa[],size[]; public static void main(String[] args) { int n=in.nextInt(),m=in.nextInt(); fa=new int[n+1];//父节点数组 size=new int[n+1];//记录每个节点包含的节点个数,每颗树的调用用size[find(i)] for(int i=1;i<=n;i++){ fa[i]=i;//每个节点的父节点首先标记为自己 size[i]=1;//每个节点都是一棵树,节点个数为1 } while(m-->0) { String op=in.next(); if(op.equals("C")) { int u=in.nextInt(),v=in.nextInt(); int fu=find(u),fv=find(v);//不在同一棵树上 if(fu!=fv) { fa[fu]=fv;//将u的根节点的父节点标记为v的根节点 size[fv]+=size[fu];//fv为整颗树的根,所以用size[fv]加 } }else if(op.equals("Q1")) { int u=in.nextInt(),v=in.nextInt(); int fu=find(u),fv=find(v); out.println(fu==fv?"Yes":"No");//根节点是否相同 }else { int u=in.nextInt(); out.println(size[find(u)]); } } out.close(); out.close(); } public static int find(int x){ if(fa[x]!=x) fa[x]=find(fa[x]); return fa[x]; } static FastReader in=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static class FastReader{ static BufferedReader br; static StringTokenizer st; FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next() { String str=""; while(st==null||!st.hasMoreElements()) { try { str=br.readLine(); }catch(IOException e) { throw new RuntimeException(e); } st=new StringTokenizer(str); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } }
信息
- ID
- 52
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 4
- 标签
- 递交数
- 27
- 已通过
- 14
- 上传者