How Many Tables

How Many Tables

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


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. 
【ps:输入的开始是test_cases的个数,
这边有两组数据{(1,2),(2,3),(4,5)} 跟{(2,5)}】
Then T test cases follow.【这话是废话】 
Each test case starts with two integers N and M(1<=N,M<=1000). 【每一组数据以N和M开头】
N indicates the number of friends, 【N代表每一组数据的数量】
the friends are marked from 1 to N. 【数量被标记为1,2,3、、、N】
Then M lines follow. 【下面中有M行 ,sample input中M的值为3,表示下列三行】
1 2 
2 3 
4 5
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    //【两组数据{(1,2),(2,3),(4,5)} 跟{(2,5)}】
5 3   //第一组数据中有1、2、3、4、5 这5个数据
1 2   //1和2 认识
2 3   //2和3 认识
4 5   //4和5 认识

5 1    //第二组中有1、2、3、4、5 这5个数据
2 5    //2和5认识   (1、3、4都互相不认识啊!!!!)


Sample Output

2 4   //第一组需要2张桌子  第二组需要4张桌子
代码:
#include<stdio.h>
int num[1100];
int find(int x) //找爸爸
{
 while(parent[x]!=x)
 return  parent[x];
}
void  unio(int x,int y)
{
     //并集操作
int parentx=find(x);

int parenty=find(y);

if(parentx!==parenty)

{  //x跟y不在一棵树上面,所有可以把他们加到同一棵书上面

  parent[x]=y;

}

int main()
{
 int t,n,m,i,x,y,count;
 scanf("%d",&t);//输入test case的个数
 while(t--)
 {
  scanf("%d%d",&n,&m); //n是总共朋友的数量
  for(i=1;i<=n;i++)//初始化自己的爸爸是自己
   parent[i]=i;
  for(i=1;i<=m;i++) 
  {
   scanf("%d%d",&x,&y);
   unio(x,y);
  }
  for(count=0,i=1;i<=n;i++)
   if(parent[i]==i)//就是现在还有多少个朋友的爸爸是自己的
    count++;
  printf("%d\n",count);
 }
 return 0;
}

no picture SAY  xx 其实只要自己画一个图就明白了啦



应该是最简单的并查集了,不过对于我这样的初学者来说,就是一个字啊!难!

猜你喜欢

转载自blog.csdn.net/chitiaosuo4319/article/details/80038448
今日推荐