查并集算法 How Many Tables

快来打我* 2024-02-18 22:52 145阅读 0赞






How Many Tables

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


 

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

  1.  

2 5 3 1 2 2 3 4 5 5 1 2 5

 

 

Sample Output

  1.  

2 4

 

 

Author

Ignatius.L

 

这题我快被格式坑死了

#include
#include
#include
using namespace std;
int a[1001],par[1001];
int find(int x) 查并集主要是这部分,假设各个
{
int r=x,j;
while(x!=par[x]) par记录x的前驱,
x=par[x];
while(r!=x) 压缩路经
{
j=par[r];
par[r]=x;
r=j;
}
return x; 找到源点
}
int join(int n,int m)
{
int fx=find(n);
int fy=find(m);
if(fx!=fy)
{
par[fy]=fx; 这是个技巧,以左为父;
return 1;
}
return 0;
}
int main()
{
int T,i,j,n,m,x,y,s=0;
cin>>T;
getchar();
while(T—)
{
int k=0;

cin>>n>>m;
for(i=1;i<=n;i++)
{
par[i]=i;
a[i]=i;
}
for(i=1;i<=m;i++)
{
cin>>x>>y;
join(x,y);
}
//for(i=1;i<=n;i++)
//cout<<par[i]<<” “;
//cout<<endl;
for(i=1;i<=n;i++)
{
if(par[i]==i)
{

k++;
}
}
cout<<k<<endl;
}
return 0;
}

发表评论

表情:
评论列表 (有 0 条评论,145人围观)

还没有评论,来说两句吧...

相关阅读