有n个国家,可以结盟或退盟。问最后有多少个联盟。(最初他们各自为盟)
http://acm.fzu.edu.cn/problem.php?pid=2155
id[i]表示i国真正的编号,f[i]表示编号为i的国家所属的联盟。
结盟的时候,用并查集合并;退盟的时候将id[x]指向一个新的编号。
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
#define pb push_back
const int inf = 0x3f3f3f3f;
const int mod = 1000000007;
const int maxn = 1000000 + 10;
int n, m, x, y, cas = 0;
int f[maxn], id[maxn];
char op[2];
int findset(int x){
return x == f[x] ? x : f[x] = findset(f[x]);
}
int main(){
while(~scanf("%d%d", &n, &m)){
if(!n && !m) break;
int cnt = n;
for(int i=0; i<maxn; i++) f[i] = id[i] = i;
while(m--){
scanf("%s", op);
if(op[0] == 'M'){
scanf("%d%d", &x, &y);
int xx = findset(id[x]);
int yy = findset(id[y]);
if(xx != yy) f[yy] = xx;
}
else{
scanf("%d", &x);
id[x] = cnt++;
}
}
vector<int> V;
V.clear();
for(int i=0; i<n; i++) V.pb(findset(id[i]));
sort(V.begin(), V.end());
int ans = 0, tmp = inf;
for(int i=0; i<n; i++)
if(V[i] != tmp){
ans++;
tmp = V[i];
}
printf("Case #%d: %d\n", ++cas, ans);
}
return 0;
}