prim

11  •  3个月前


#include <iostream>
#include <vector>
#include <queue>
#include <utility>
#include <functional>

using namespace std;

const long long INF = 1e18;

struct Edge {
    int to;
    long long weight;
    Edge(int t, long long w) : to(t), weight(w) {}
};

long long prim(int n, vector<vector<Edge>>& adj) {
    vector<bool> inMST(n + 1, false);
    vector<long long> minEdge(n + 1, INF);
    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;

    minEdge[1] = 0;
    pq.push({0, 1});

    long long mst_weight = 0;
    int mst_edges = 0;

    while (!pq.empty()) {
        auto [weight, u] = pq.top();
        pq.pop();

        if (inMST[u]) continue;

        inMST[u] = true;
        mst_weight += weight;
        mst_edges++;

        for (const auto& edge : adj[u]) {
            int v = edge.to;
            long long w = edge.weight;
            if (!inMST[v] && w < minEdge[v]) {
                minEdge[v] = w;
                pq.push({w, v});
            }
        }
    }

    if (mst_edges != n) {
        return -1; // 图不连通
    } else {
        return mst_weight;
    }
}

int main() {
    int n, m;
    cin >> n >> m;

    vector<vector<Edge>> adj(n + 1);
    for (int i = 0; i < m; i++) {
        int u, v;
        long long w;
        cin >> u >> v >> w;
        adj[u].emplace_back(v, w);
        adj[v].emplace_back(u, w);
    }

    long long result = prim(n, adj);
    if (result == -1) {
        cout << "orz" << endl;
    } else {
        cout << result << endl;
    }

    return 0;
}

评论:

请先登录,才能进行评论