Ubiquitous Religions POJ - 2524
并查集
#include<iostream> #include<algorithm> #define fori for(i=0;i<n;i++) #define fori1 for(i=1;i<=n;i++) #define ll long long const ll mod = 1e9 + 7; const int maxn = 50050; using namespace std; ll s[maxn + 7]; ll height[maxn + 7]; void init_set()//初始化 { s[0] = 0; for (int i = 1; i <= maxn; i++) { s[i] = i; height[i] = 0;//树的高度 } } ll find_set(ll x)//查找 { ll r = x;//找到根结点 while (s[r] != r)r = s[r]; ll i = x, j; while (i != r) { j = s[i];//用临时变量j记录 s[i] = r;//把路径上元素的集改为根结点 i = j; } return r; } void union_set(ll x, ll y)//合并 { x = find_set(x); y = find_set(y); if (height[x] == height[y]) { height[x] = height[x] + 1; s[y] = x;//合并,树的高度加一 } else { if (height[x] < height[y])s[x] = y;//把矮树并到高树上,高树的高度保持不变 else s[y] = x; } } int main() { ll i=1, j, k; ll n, m, t; ll x, y,ret=0; ll ans = 0,sum=1; while (cin >> n >> m) { ret++; if (n == 0 && m == 0) break; init_set(); for (i = 0; i < m; i++) { cin >> x >> y; union_set(x, y); } ans = 0; fori1 if (find_set(i) == i) ans++; cout << "Case " << ret << ": " << ans << endl; } }