Hdu1213 How Many Tables【并查集】

http://acm.hdu.edu.cn/showproblem.php?pid=1213

题目大意:给出一些关系,求有几个集合。

“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.”

并查集裸体,直接上代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
template <class T> void checkmin(T &t,T x) {if(x < t) t = x;}
template <class T> void checkmax(T &t,T x) {if(x > t) t = x;}
template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;}
template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;}
typedef pair <int,int> PII;
typedef pair <double,double> PDD;
typedef long long ll;
#define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++)
int T , n , m;
const int N = 1010;
int f[N];
int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); }
void Union(int x,int y) {
    int a = find(x) , b = find(y);
    f[a] = f[b] = f[x] = f[y] = min(a , b);
}
int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=(n);i++) f[i] = i;
        while(m --) {
            int u  , v;
            scanf("%d%d",&u,&v);
            Union(u,v);
        }
        int ans = 0;
        for(int i=1;i<=n;i++) if(find(i) == i) ans ++;
        printf("%d\n" , ans);
    }
    return 0;
}

 

 

 

posted @ 2013-03-28 23:30  aiiYuu  阅读(136)  评论(0)    收藏  举报