HDU 1213 How Many Tables
How Many Tables
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 39046 Accepted Submission(s): 19454
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.
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
Recommend
Problem Idea
【题意】
题意为:给出一个有N(0<N<=1000)个顶点的无向图(顶点编号0到N-1), 然后依次给出它的M(0<M<=1000)条边,要求计算最后该图的连通分量总数。
输入:首先是T(1<=T<=25),表示实例个数。然后每个实例第一行为N和M(1<=N,M<=1000),表示整数从1到N,接下来有M对整数。
输出:连通分量个数。
【类型】
并查集求无向图的连通分量
【分析】
并查集模板题,入门。
【注意】
memset(fa,-1,sizeof(fa));//每轮输入样例前都要重置一遍fa
int cnt=n;//初始化n个独立的节点的连通分量个数为n,要在输入n以后
小结:
如何快速计算无向图还剩多少个连通分量?
初始连通分量为n,每进行一次有效的bind(当bind返回1时表示进行了有效的合并)操作,就会使得连通分量数目-1。所以最终连通分量数目为:n – 有效bind操作的次数。
AC代码
初始连通分量为n,每进行一次有效的bind(当bind返回1时表示进行了有效的合并)操作,就会使得连通分量数目-1。所以最终连通分量数目为:n – 有效bind操作的次数。
AC代码
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int nmax=1000+5;
int fa[nmax];//区别fa是父节点,findset是根节点
int findset(int x){
return fa[x]==-1 ? x :fa[x]=findset(fa[x]);
}
int bind(int u,int v){
int fu=findset(u);
int fv=findset(v);
if(fu!=fv){
fa[fu]=fv;
return 1;
}
return 0;
}
int main(int argc, char** argv) {
int T;//T为输入样例轮数
scanf("%d",&T);
//cin>>T;
int n,m;//n为图中的节点数,m为已知的连通边数
int u,v;//连通边的起点和终点
while(T--){
memset(fa,-1,sizeof(fa));//每轮输入样例前都要重置一遍fa
scanf("%d%d",&n,&m);
int cnt=n;//初始化n个独立的节点的连通分量个数为n
for(int i=1;i<=m;i++){
scanf("%d%d",&u,&v);
cnt-=bind(u,v);//每次向图中增加连通的边,用初始连通分量数减去增加的两条边产生的连通分量数
//每次的cnt表示求出当前的连通分量数
}
printf("%d\n",cnt);
}
return 0;
}