1 条题解

  • 1
    @ 2026-9-14 20:02:13
    #include <iostream>
    #include <vector>
    #include <set>
    using namespace std;
    
    struct DSU {
        vector<int> p;
        DSU(int n) : p(n + 1) {
            for (int i = 1; i <= n; ++i) p[i] = i;
        }
        int find(int x) {
            while (p[x] != x) {
                p[x] = p[p[x]];   // 路径压缩
                x = p[x];
            }
            return x;
        }
        void unite(int a, int b) {
            a = find(a); b = find(b);
            if (a != b) p[a] = b;
        }
    };
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int n, m;
        cin >> n >> m;
    
        DSU dsu(2 * n);   // 1..n 为人,n+1..2n 为各自敌人集合代表
        for (int i = 0; i < m; ++i) {
            char p;
            int x, y;
            cin >> p >> x >> y;
            if (p == 'F') {
                dsu.unite(x, y);
            } else {  // 'E'
                dsu.unite(x, y + n);
                dsu.unite(y, x + n);
            }
        }
    
        set<int> roots;
        for (int i = 1; i <= n; ++i) roots.insert(dsu.find(i));
        cout << roots.size() << '\n';
        return 0;
    }
    
    
    
    • 1

    信息

    ID
    1313
    时间
    1000ms
    内存
    256MiB
    难度
    8
    标签
    递交数
    395
    已通过
    48
    上传者