您的位置:首页 > 其它

HDU1213 How Many Tables

2014-03-17 11:21 411 查看
思考:并查集入门题目。

#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
const int bound = 1001;
int f[1000+10];
int gn, gm;

int getFather(int x) {
if(x == f[x]) return x;
else return f[x] = getFather(f[x]);
}

int main()
{
int T;
int x, y;
scanf("%d", &T);
while(T--) {
scanf("%d%d", &gn, &gm);
for(int i = 1; i < bound; i++) f[i] = i; // f[x] = i; Segmetn fault.
for(int i = 0; i < gm; i++) {
scanf("%d%d", &x, &y);
int t1 = getFather(x);
int t2 = getFather(y);
if(t1 != t2) {
f[t1] = t2;
}
}
int ans = 0;
for(int i = 1; i <= gn; i++) {
if(i == f[i]) ans++;
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: