简单查并集 HDU 1213

 
 

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. 
InputThe 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. OutputFor 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

#include<iostream>
#include<queue>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
int main() {
	int N,n,num,w,i,j,p,a,b,ans,k[1005];
	cin>>N;	//样例数量 
	for(i=0;i<N;i++) {
		memset(k,0,sizeof(k));	//初始化,一开始都没有爸爸 
		ans=0;
		cin>>n>>num;	//人数,输入的连接数 
		for(j=1;j<=num;j++) {
			cin>>a>>b;
			if(k[a]==0) {
				if(k[b]!=0) { //仅b有爸爸时 
					k[a]=k[b]; //使a和b有共同爸爸 
				}
				if(k[b]==0) { //a和b都没有爸爸时 
					k[b]=b;	//指向自己 
					k[a]=k[b];	//使a和b有共同爸爸 
					ans++;	//多一个群 
				}
			} 
			else {
				if(k[b]==0) {	//仅a有爸爸时 
					k[b]=k[a];	//使a和b有共同爸爸 
				} 
				if(k[b]!=0&&k[a]!=k[b]) {
					w=k[b];
//因为后来合并时会改变k[b]的值,所以要先用w保留值 
					ans--;	//合并群时,减一 
					for(p=1;p<=n;p++) {	//暴力搜索一遍,合并群 
						if(k[p]==w) {
							k[p]=k[a];
						} 
					}
				}
			}
		}
		for(p=1;p<=n;p++) {	//对于没有被赋值的元素,独立成群 
			if(k[p]==0) {
				ans++;
			}
		}
		printf("%d\n",ans);
	}
} 

猜你喜欢

转载自blog.csdn.net/littlewhitelv/article/details/79954298