Codevs2597 团伙
还是做题太少啊,然而NOIP了。
代码简单易懂:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAXN (1010)
int ans;
int fa[MAXN], en[MAXN];
int find(int x)
{
int t, r = x;
while(r != fa[r]) r = fa[r];
while(x != r) {t=fa[x];fa[x]=r;x=t;}
return r;
}
void lianjie(int x, int y)
{
int fx = find(x);
int fy = find(y);
if(fx != fy)
{
fa[fx] = fy;
-- ans; //每连接一个就少一个团伙
}
}
char t[5];
int main()
{
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; ++ i)
fa[i] = i;
ans = n; // 刚开始共有n个团伙
for(int i = 1; i <= m; ++ i)
{
scanf("%s", t);
int p, q;
scanf("%d%d", &p, &q);
if(t[0] == 'F')
lianjie(p,q);
else {
if(en[p]) lianjie(en[p], q); // 如果 p 有敌人,那么q和他就是朋友
en[p] = q;
if(en[q]) lianjie(en[q], p);
en[q] = p;
}
}
cout << ans << endl;
return 0;
}