(step5.1.3)hdu 1213( How Many Tables——1213)

题目大意:输入两个整数n,m。分别表示点数、对点的操作的次数。在接下来的m行中,每行有两个整数a,b。表示a和b是好朋友。(不是好朋友的不能坐在同一个桌子上)

。求需要多少张桌子


解题思路:并查集

1)用total来记录所需要的桌子数。如果没合并一次total就减1.



代码如下:

 

/*
 * 1213_1.cpp
 *
 *  Created on: 2013年8月23日
 *      Author: Administrator
 */

#include <iostream>

using namespace std;

int father[1000];
int total;

int find(int x){
	int r,i,j;

	r = x;
	while( r != father[r]){
		r = father[r];
	}

	i = x;
	while( i != r){
		j = father[i];
		father[i] = r;
		i = j;
	}

	return r;
}

void join(int x , int y){
	int fx = find(x);
	int fy = find(y);
	if(fx != fy){
		father[fx] = fy;
		total--;
	}
}

void make_set(int n){
	int i;
	for(i = 1 ; i <= n ; ++i){
		father[i] = i;
	}
}


int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		int n,m;
		scanf("%d%d",&n,&m);
		make_set(n);
		total = n;

		int i;
		for( i = 1 ; i <= m ; ++i){
			int a,b;
			scanf("%d%d",&a,&b);
			join(a,b);
		}
		printf("%d\n",total);
	}
}



 

 

posted @ 2013-08-25 20:22  pangbangb  阅读(177)  评论(0编辑  收藏  举报