hdu 1213 简单并查集

/*
* hdu1213/win.cpp
* Created on: 2011-11-5
* Author : ben
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <functional>
#include <numeric>
#include <cctype>
using namespace std;
const int MAXN = 1010;
int M, N;
int parent[MAXN];

int myfind(int i) {
int r = i;
while (parent[r] != r) {
r = parent[r];
}
return r;
}

inline void merge(int a, int b) {
if (a < b) {
parent[b] = a;
} else {
parent[a] = b;
}
}

int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif
int T, a, b, ans;
scanf("%d", &T);
while (T--) {
scanf("%d%d", &N, &M);
for (int i = 1; i <= N; i++) {
parent[i] = i;
}
for (int i = 0; i < M; i++) {
scanf("%d%d", &a, &b);
merge(myfind(a), myfind(b));
}
ans = 0;
for (int i = 1; i <= N; i++) {
if (parent[i] == i) {
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}
posted @ 2011-11-05 16:52  moonbay  阅读(186)  评论(0编辑  收藏  举报