Cod sursa(job #2551144)

Utilizator minecraft3Vintila Valentin Ioan minecraft3 Data 19 februarie 2020 16:19:38
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

#define N 400005
#define M 800005
#define INF 1000000000
	
int d[N], vf[M], urm[M], lst[N], cst[M], pred[N], nr, n;
bool viz[N];

void add_graph(int x, int y, int c) {
    vf[++nr] = y;
    cst[nr] = c;
    urm[nr] = lst[x];
    lst[x] = nr;
}

typedef pair<int, int> iPair;

int cost;
void prim() {
    priority_queue< iPair, vector<iPair>, greater<iPair> > pq;
    d[1] = 0;
	
    for(int i = 2; i <= n; ++i)
        d[i] = INF;
	
    pq.push(make_pair(d[1], 1));
    while(!pq.empty()) {
        int x = pq.top().second;
        pq.pop();
        if(!viz[x])
            cost += d[x];

        viz[x] = true;
        for(int p = lst[x]; p; p = urm[p]) {
            int y = vf[p], c = cst[p];
            if(!viz[y] && c < d[y]) {
                d[y] = c;
                pq.push(make_pair(d[y], y));
                pred[y] = x;
            }
        }
    }
}
	
int main() {
    ifstream fin("apm.in");
    ofstream fout("apm.out");
	
    int m, x, y, z;
    fin >> n >> m; do {
        fin >> x >> y >> z;
        add_graph(x, y, z);
        add_graph(y, x, z);
    } while(--m);

    prim();

    fout << cost << '\n' << n-1;
    for(int i = 1; i <= n; ++i)
        if(pred[i])
            fout << '\n' << i << ' ' << pred[i];
    return 0;
}