0
点赞
收藏
分享

微信扫一扫

HDUOJ---1213How Many Tables

青乌 2022-03-18 阅读 52


How Many Tables

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 9828    Accepted Submission(s): 4872


Problem Description 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.  


Input The 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.  


Output For 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  


Author Ignatius.L  


Source ​​杭电ACM省赛集训队选拔赛之热身赛​​   代码: 并查集,模板的运用..

HDUOJ---1213How Many Tables_javaHDUOJ---1213How Many Tables_HDUOJ_02

1     #include<stdio.h>
2 #include<string.h>
3 #define maxn 1005
4 int father[maxn+1],rank[maxn+1];
5
6 /*³õʼ»¯*/
7 void init(int n)
8 {
9 for(int i=1;i<=n;i++)
10 {
11 father[i]=i;
12 rank[i]=1;
13 }
14 }
15
16 /*²é*/
17 int setfind(int x)
18 {
19 if(father[x]==x)
20 return x;
21 return setfind(father[x]);
22 }
23
24 /*²¢*/
25 void Union(int a,int b)
26 {
27 int x=setfind(a);
28 int y=setfind(b);
29 if(x!=y)
30 {
31 if(rank[x]>rank[y])
32 {
33 father[y]=x;
34 rank[x]+=rank[y];
35 }
36 else
37 {
38 father[x]=y;
39 rank[y]+=rank[x];
40 }
41 }
42 }
43
44 int main()
45 {
46 int t,m,n,i,a,b;
47 /* freopen("test.in","r",stdin);
48
49 freopen("test.out","w",stdout);
50 */
51 scanf("%d",&t);
52 while(t--)
53 {
54 scanf("%d%d",&n,&m);
55 init(n);
56 for(i=0;i<m;i++)
57 {
58 scanf("%d%d",&a,&b);
59 Union(a,b);
60 }
61 int cnt=0;
62 for(i=1;i<=n;i++)
63 if(father[i]==i)
64 cnt++;
65 printf("%d\n",cnt);
66 }
67 return 0;
68 }

View Code



编程是一种快乐,享受代码带给我的乐趣!!!


举报

相关推荐

0 条评论