How Many TablesTime 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.
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
|
这题我快被格式坑死了
#include<iostream>
#include<string.h>
#include<algorithm>
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;
}