1 条题解

  • 1
    @ 2024-7-25 13:43:02

    参考答案:

    #include<iostream>
    #include<algorithm>
    
    using namespace std;
    
    const int N = 100010, M = 2 * N, INF = 0x3f3f3f3f;
    int p[N];
    int n, m;
    
    struct Edge
    {
        int a, b, c;
        bool operator<(const Edge& W) const
        {
            return c < W.c;
        }
    }edge[M];
    
    int find(int x)
    {
        if (p[x] != x) p[x] = find(p[x]);
        return p[x];
    }
    
    int kruskal()
    {
        sort(edge + 1, edge + m + 1);
        int res = 0, t = 0;
    
        for (int i = 1; i <= m; ++i)
        {
            int a = edge[i].a, b = edge[i].b, c = edge[i].c;
            a = find(a), b = find(b);
            if (a != b)
            {
                p[a] = b;
                res += c;
                t++;
            }
        }
    
        if (t < n - 1) return INF;
        return res;
    }
    int main()
    {
        cin >> n >> m;
    
        for (int i = 1; i <= n; ++i) p[i] = i;
        for (int i = 1; i <= m; ++i)
        {
            cin >> edge[i].a >> edge[i].b >> edge[i].c;
        }
    
        int t = kruskal();
    
        if (t == INF) cout << "Not exist" << endl;
        else cout << t << endl;
    
        return 0;
    }
    
    • 1

    信息

    ID
    103
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    2
    已通过
    2
    上传者