Cod sursa(job #2621666)

Utilizator CristiPopaCristi Popa CristiPopa Data 30 mai 2020 16:30:40
Problema Arbore partial de cost minim Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>

#define NMAX 200010
#define DMAX 1e9
using namespace std;

int n , m, cost;
vector<pair<int, int>> adj[NMAX];
int dist[NMAX], parent[NMAX];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
bool used[NMAX];

int main()
{
    cost = 0;
    ifstream fin("apm.in");
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        dist[i] = DMAX;
        parent[i] = 0;
        used[i] = false;
    }
    for (int i = 1, x, y, c; i <= m; ++i) {
        fin >> x >> y >> c;
        adj[x].push_back({c, y});
        adj[y].push_back({c, x});
    }
    fin.close();
    dist[1] = 0;
    q.push({dist[1], 1});
    for (int i = 1; i <= n; ++i) {
        int node;
        do {
            node = q.top().second;
            q.pop();
        } while (used[node]);

        cost += dist[node];
        used[node] = true;

        for (auto &neigh : adj[node]) {
            if (!used[neigh.second] && neigh.first < dist[neigh.second]) {
                dist[neigh.second] = neigh.first;
                parent[neigh.second] = node;
                q.push({neigh.first, neigh.second});
            }
        }
    }

    ofstream fout("apm.out");
    fout << cost << endl << n - 1 << endl;
    for (int i = 2; i <= n; ++i) {
        fout << i << ' ' << parent[i] << endl;
    }
    fout.close();
    return 0;
}