Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
2 5 3 1 2 2 3 4 5 5 1 2 5
24
分析: 并查集水题。。。。
import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static int n,m,cnt,k; static int[] f = new int[1005]; //寻找父节点 static int find(int x){//提交以后我发现这种方式比我原来的方式(就是注释的部分),快很多。。。。 int t= x; while(t!=f[t]){ t=f[t];//路径压缩 } return t; // if(f[x]==x) // return x; // else // return f[x]=find(f[x]); } //合并集合 static void merge(int x,int y){ int t1 = find(x); int t2 = find(y); if(t1!=t2) f[t1]=t2; } public static void main(String[] args) { int k = in.nextInt(); while(k-->0){ cnt=0; n = in.nextInt(); m = in.nextInt(); for (int i = 1; i <= n; i++) { f[i]=i; } int x,y; for (int i = 0; i < m; i++) { x = in.nextInt(); y = in.nextInt(); merge(x,y); } for (int i = 1; i <= n; i++) { if(f[i]==i) cnt++; } System.out.println(cnt); } } }