acwing 784. 强盗团伙

传送门

经典并查集问题

#include

using namespace std;
const int N = 1010;

int n, m;
vector<int> e[N]; ///记录敌人
int f[N];

int Find(int x)
{
    return f[x] = (x==f[x])?x:Find(f[x]);
}
void merge(int x, int y)
{
    x = Find(x), y = Find(y);
    if(x == y) return ;
    if(x < y) f[y] = x;
    else f[x] = y;
}
int main()
{
    scanf("%d%d", &n, &m);
    for(int i = 1;i <= n; ++i) f[i] = i;
    while(m--)
    {
        char op;
        int x, y;
        scanf(" %c%d%d", &op, &x, &y);
        if(op == 'F'){
            merge(x, y);
        }else {
            e[x].push_back(y);
            e[y].push_back(x);
        }
    }
    for(int i = 1; i <= n; ++i) { ///敌人的敌人就是朋友
        for(int x:e[i])
        for(int y:e[i])
        merge(x, y);
    }
    int c= 0;
    for(int i = 1;i <= n; ++i)
    if(Find(i) == i) c++;
    printf("%d\n", c);
    return 0;
}

你可能感兴趣的:(并查集)