1 条题解

  • 0
    @ 2025-4-12 9:28:57

    按 kruskal 算法加边,直到连通块数量够了为止

    #include <bits/stdc++.h>
    using namespace std;
    const int MAXN = 1000;
    const int MAXM = 10000;
    int n, m, k;
    // e[i] 存第 i 条边 {边权,{起点,终点}}
    pair<int, pair<int, int>> e[MAXM + 5];
    // 并查集
    int fa[MAXN + 5];
    int findFa(int x)
    {
        if (x == fa[x])
            return x;
        return fa[x] = findFa(fa[x]);
    }
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> m >> k;
        for (int i = 1; i <= m; i++)
        {
            // cin >> e[i].second.first >> e[i].second.second >> e[i].first;
            int u, v, w;
            cin >> u >> v >> w;
            e[i] = {w, {u, v}};
        }
    
        sort(e + 1, e + m + 1);
        int num = n; // 连通块数量
        int ans = 0; // 选择的边的权值之和
        for (int i = 1; i <= n; i++)
            fa[i] = i;
        for (int i = 1; num > k && i <= m; i++)
        {
            int u = e[i].second.first;
            int v = e[i].second.second;
            int w = e[i].first;
            int faU = findFa(u);
            int faV = findFa(v);
            if (faU == faV)
                continue;
            num--;
            fa[faU] = faV;
            ans += w;
        }
        if (num != k)
            cout << "No Answer";
        else
            cout << ans;
        return 0;
    }
    

    信息

    ID
    2012
    时间
    1000ms
    内存
    125MiB
    难度
    3
    标签
    递交数
    28
    已通过
    14
    上传者