Cod sursa(job #3205909)

Utilizator TeddyDinutaDinuta Eduard Stefan TeddyDinuta Data 20 februarie 2024 22:29:57
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
int min_edge[200005], min_node[200005];
vector<pair<int, int>> adj[200005];
bool chosen[200005];
int n, m, x, y, c;
int cmin;
vector<pair<int, int>> ans;

void prim(int node) {
    for (int i = 1; i <= n; i++) {
        min_node[i] = -1;
        min_edge[i] = 1e9;
    }

    min_edge[node] = 0;
    q.push({0, node});

    while (!q.empty()) {
        int x = q.top().second;
        int c = q.top().first;
        q.pop();

        if (chosen[x])
            continue;
        if (min_node[x] != -1) {
            ans.push_back({min_node[x], x});
        }

        chosen[x] = 1;
        cmin += c;

        for (auto it : adj[x]) {
            if (!chosen[it.first] && it.second < min_edge[it.first]) {
                min_edge[it.first] = it.second;
                min_node[it.first] = x;
                q.push({min_edge[it.first], it.first});
            }
        }
    }

}

int main()
{
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    in >> n >> m;
    for (int i = 1; i <= m; i++) {
        in >> x >> y >> c;
        adj[x].push_back({y, c});
        adj[y].push_back({x, c});
    }

    prim(1);

    out << cmin << '\n' << ans.size() << '\n';
    for (auto it : ans) {
        out << it.first << " " << it.second << '\n';
    }
    return 0;
}