敲响警钟!
查看原帖
敲响警钟!
1079004
MelancholyZ楼主2024/12/21 18:41

这里有一个问题是并查集的合并顺序问题 在之前由于都是1-n的合并,所以合并顺序都不会影响最终结果

但这次有2n个点!!

也就是说如果你把1-n的点的父亲指向n+1-2n,这样再用fa[i] == i 计数就会出问题!

所以这里我们都将父亲的范围设定在1-n 也就是需要关注顺序问题

AC代码如下

#include <bits/stdc++.h>
using namespace std;
int n, m;
const int N = 2e4 + 5;
int fa[N];
int find(int x)
{
    if (fa[x] == x)
        return x;
    return fa[x] = find(fa[x]);
}
void update(int x, int y)
{
    x = find(x), y = find(y);
    if (x != y)
        fa[x] = fa[y];
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int i = 1; i <= 2*n; i++) fa[i] = i;
    for (int i = 1, a, b; i <= m; i ++){
        char o;
        cin >> o >> a >> b;
        if(o == 'F') update(a,b);
        else{
            update(a+n,b);
            update(b+n,a);
        }
    }
    int ans = 0;
    //for(int i = 1; i <= n; i ++) cout << fa[i] << ' '; 
    //cout << endl;
    for(int i = 1; i <= n; i ++){
        if(fa[i] == i) ans ++;
    }
    cout << ans << endl;
    return 0;
}
2024/12/21 18:41
加载中...