您的位置:首页 > 其它

hdu 1213 How Many Tables

2015-01-02 13:38 381 查看
acm.hdu.edu.cn/showproblem.php?pid=1213

简单并查集,统计集合个数类型

AC代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAX = 1010;
int n,m,father[MAX];

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

int Find(int x){
	if(x != father[x])
		father[x] = Find(father[x]);
	return father[x];
}

int main(){
	int ca;
	scanf("%d",&ca);
	while(ca--){
		scanf("%d%d",&n,&m);
		Init();
		for(int i=0; i<m; i++){
			int a,b;
			scanf("%d%d",&a,&b);
			int u = Find(a),v = Find(b);
			// cout << u << " " << v << endl;
			father[v] = u;
		}
		int ans = 0;
		for(int i=1; i<=n; i++)
			if(father[i] == i) ans++;
		printf("%d\n",ans);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: