HDU1213--How Many Tables
How Many Tables
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9097 Accepted Submission(s): 4448
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省赛集训队选拔赛之热身赛
Recommend
Eddy
简单并查集
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<iostream> 5 #include<cmath> 6 using namespace std; 7 8 int parent[1001]; 9 int n,m; 10 11 void Ufset() 12 { 13 int i; 14 for(i=1;i<=n;i++) 15 { 16 parent[i]=-1; 17 } 18 } 19 20 int Find(int x) 21 { 22 int s; 23 for(s=x;parent[s]>0;s=parent[s]){} 24 while(s!=x) 25 { 26 int temp=parent[x]; 27 parent[x]=s; 28 x=temp; 29 } 30 return s; 31 } 32 33 void Union(int R1,int R2) 34 { 35 int r1=Find(R1),r2=Find(R2); 36 int temp=parent[r1]+parent[r2]; 37 if(parent[r1]>parent[r2]) 38 { 39 parent[r1]=r2; 40 parent[r2]=temp; 41 } 42 else 43 { 44 parent[r2]=r1; 45 parent[r1]=temp; 46 } 47 } 48 49 int main() 50 { 51 int t; 52 scanf("%d",&t); 53 while(t--) 54 { 55 scanf("%d%d",&n,&m); 56 Ufset(); 57 while(m--) 58 { 59 int u,v; 60 scanf("%d%d",&u,&v); 61 if(Find(u)!=Find(v)) 62 { 63 Union(u,v); 64 } 65 } 66 int sum=0; 67 int ans=0; 68 for(int i=1;i<=n;i++) 69 { 70 if(abs(parent[i])>1&&parent[i]<0) 71 { 72 sum++; 73 ans+=abs(parent[i]); 74 } 75 } 76 if(ans==n) 77 printf("%d\n",sum); 78 else 79 printf("%d\n",sum+n-ans); 80 } 81 return 0; 82 }