Cod sursa(job #3358461)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 16 iunie 2026 20:06:21
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
// Prim's algorithm
//
// Find the minimum spanning tree (MST) - a subset of the original graph that
// contains all nodes, but only n - 1 edges with the property that the total
// weight of the edges is minimal.
//
// Complexity:
// - dense graph: O(N^2)
// - sparse graph: O(M * logN)

#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<vector<pair<int, int>>> adj;
vector<int> parent;
vector<pair<int, int>> ans;

int prim(int start)
{
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        pq;

    vector<int> min_weight(n, INT_MAX);
    vector<int> selected(n, false);
    int total_weight = 0;

    min_weight[start] = 0;
    pq.push({0, start});

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

        if (weight != min_weight[node])
            continue;

        selected[node] = true;
        total_weight += weight;

        if (parent[node] != -1)
            ans.push_back({parent[node], node});

        for (auto [next, next_weight] : adj[node]) {
            if (!selected[next] && next_weight < min_weight[next]) {
                min_weight[next] = next_weight;
                parent[next] = node;
                pq.push({next_weight, next});
            }
        }
    }

    return total_weight;
}

int main()
{
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);

    cin >> n >> m;
    adj.resize(n);
    parent.resize(n, -1);
    ans.clear();

    for (int i = 0; i < m; i++) {
        int x, y, w;
        cin >> x >> y >> w;
        x--;
        y--;
        adj[x].push_back({y, w});
        adj[y].push_back({x, w});
    }

    cout << prim(0) << '\n';
    cout << ans.size() << '\n';
    for (auto [in, out] : ans)
        cout << in + 1 << ' ' << out + 1 << '\n';

    return 0;
}