1 solutions

  • 0
    @ 2025-6-18 11:45:04

    利用并查集,将节点合并到集合中,统计连通分量数量;根据树结构特性(nn个节点需n1n - 1条边),计算多余边数和需新增边数,二者相加得最少操作次数。 统计连通分量个数 ansans;通过公式mn+2ans1m - n + 2 * ans - 1算出最少操作次数 ,其中mm是现有边数,nn是节点数。

    #include<bits/stdc++.h>
    using namespace std;
    #define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
    #define ll long long
    const ll N = 1e6 + 1;
    
    ll n, m;
    ll p[N];  
    
    ll finds(ll x) {
        if (p[x] != x) p[x] = finds(p[x]);
        return p[x];
    }
    
    void mset(ll x, ll y) {
        x = finds(x), y = finds(y);
        if (x != y) p[x] = y;
    }
    
    signed main() {
        IOS;
        cin >> n >> m;
        for (ll i = 1; i <= n; i++) p[i] = i; 
    
        for (ll i = 0; i < m; i++) {
            ll x, y;
            cin >> x >> y;
            mset(x, y);
        }
    
        ll ans = 0;
        for (ll i = 1; i <= n; i++) {
            if (p[i] == i) ans++;
        }
        cout << m - n + 2 * ans - 1 << endl;
        return 0;
    }
    
    • 1

    Information

    ID
    1506
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    7
    Tags
    (None)
    # Submissions
    33
    Accepted
    9
    Uploaded By