1 条题解

  • 0
    @ 2026-11-2 13:51:31

    安慰奶牛(Cheering up the Cow G) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <iostream>
    #include <vector>
    #include <numeric>
    #include <algorithm>
    using namespace std;
    
    struct Edge {
        int u, v;
        long long w;
        bool operator<(const Edge& o) const { return w < o.w; }
    };
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n, m;
        if (!(cin >> n >> m)) return 0;
        vector<long long> c(n + 1);
        long long minC = (1LL << 60);
        for (int i = 1; i <= n; ++i) {
            cin >> c[i];
            minC = min(minC, c[i]);
        }
        vector<Edge> edges(m);
        for (int i = 0; i < m; ++i) {
            int u, v;
            long long l;
            cin >> u >> v >> l;
            edges[i] = {u, v, 2LL * l + c[u] + c[v]};
        }
        sort(edges.begin(), edges.end());
        vector<int> p(n + 1);
        iota(p.begin(), p.end(), 0);
        auto find = [&](int x) {
            while (p[x] != x) x = p[x] = p[p[x]];
            return x;
        };
        long long ans = minC;
        for (const auto& e : edges) {
            int ru = find(e.u), rv = find(e.v);
            if (ru != rv) {
                p[ru] = rv;
                ans += e.w;
            }
        }
        cout << ans << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    8741
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者