标签:
Description
Input
Output
Sample Input
Sample Output
#include <iostream> #include <cstdio> #include <string> #include <queue> #include <vector> #include <map> #include <algorithm> #include <cstring> #include <cctype> #include <cstdlib> #include <cmath> #include <ctime> using namespace std; const int SIZE = 1005; int FATHET[SIZE],RANK[SIZE]; int N,M; void ini(int); int find_father(int); void unite(int,int); bool same(int,int); int main(void) { int t; int x,y; scanf("%d",&t); while(t --) { scanf("%d%d",&N,&M); ini(N); while(M --) { scanf("%d%d",&x,&y); unite(x,y); } bool vis[SIZE] = {false}; int sum = 0; for(int i = 1;i <= N;i ++) vis[find_father(i)] = true; for(int i = 1;i <= N;i ++) sum += vis[i]; printf("%d\n",sum); } return 0; } void ini(int n) { for(int i = 1;i <= n;i ++) { FATHET[i] = i; RANK[i] = 0; } } int find_father(int n) { if(n == FATHET[n]) return n; return FATHET[n] = find_father(FATHET[n]); } void unite(int x,int y) { x = find_father(x); y = find_father(y); if(x == y) return ; if(RANK[x] < RANK[y]) FATHET[x] = y; else { FATHET[y] = x; if(RANK[x] == RANK[y]) RANK[x] ++; } } bool same(int x,int y) { return find_father(x) == find_father(y); }
HDU 1213 How Many Tables (并查集)
标签:
原文地址:http://www.cnblogs.com/xz816111/p/4529043.html