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.
InputThe input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.
OutputFor each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
Sample Input
2 5 3 1 2 2 3 4 5 5 1 2 5
Sample Output
2 4
题意:有n个点,点与点之间有联系,相连的点可以分在一个集合里,问有多少个集合。输入第一行为t表示
测试样例数,然后是n,m。往下m行,每行a,b.表示a和b可以相连。
思路:简单并查集,套用模板,最后通过判断点的父类等于自己则表示一个集合。
代码:
1 #include <cstdio> 2 #include <fstream> 3 #include <algorithm> 4 #include <cmath> 5 #include <deque> 6 #include <vector> 7 #include <queue> 8 #include <string> 9 #include <cstring> 10 #include <map> 11 #include <stack> 12 #include <set> 13 #include <sstream> 14 #include <iostream> 15 #define mod 998244353 16 #define eps 1e-6 17 #define ll long long 18 #define INF 0x3f3f3f3f 19 using namespace std; 20 21 //fa[x]表示x的最远祖先 22 int fa[1005]; 23 //初始化,一开始每个点单独成集合 24 void build(int qwq) 25 { 26 for(int i=1;i<=qwq;i++) 27 { 28 fa[i]=i; 29 } 30 return ; 31 } 32 //找到x的最远祖先,并且压缩路径 33 int find(int x) 34 { 35 if(fa[x]==x) 36 { 37 return x; 38 } 39 return fa[x]=find(fa[x]); 40 } 41 //判断x,y是不是在同一个集合里,直接判断最远祖先是不是一样的 42 bool che(int x,int y) 43 { 44 return find(x)==find(y); 45 } 46 //合并x,y,我们在判断x和y是不是同一个集合里, 47 //路径压缩之后fa[x],fa[y]已经是最远祖先了, 48 //所以直接将fa[x]的父亲连接在fa[y]的祖先上 49 void mer(int x,int y) 50 { 51 if(!che(x,y)) 52 { 53 fa[fa[x]]=fa[y]; 54 } 55 return ; 56 } 57 58 int main() 59 { 60 int t; 61 scanf("%d",&t); 62 while(t--) 63 { 64 int n,m; 65 scanf("%d %d",&n,&m); 66 //初始化 67 build(n); 68 int a,b; 69 for(int i=0;i<m;i++) 70 { 71 scanf("%d %d",&a,&b); 72 //合并a,b 73 mer(a,b); 74 } 75 int ans=0; 76 //遍历所有点,如果i的父类是自己则i是它坐在集合的代表 77 //累加所有的集合数 78 for(int i=1;i<=n;i++) 79 { 80 if(find(i)==i) 81 { 82 ans++; 83 } 84 } 85 printf("%d\n",ans); 86 } 87 }