Cod sursa(job #2870410)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 12 martie 2022 12:28:53
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
#define oo 2000000001
using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

int n,m;
vector < pair < int , int > > v[200005];
int tot_cost;
int x,y,c;
int muchie[200005];
bool viz[200005];
priority_queue < pair < int , int > , vector < pair < int , int > > , greater < pair < int , int > > > pq;
int tata[200005];

void read() {
    f >> n >> m;
    for (int i=1;i<=m;i++) {
        f >> x >> y >> c;
        v[x].push_back({y,c});
        v[y].push_back({x,c});
    }
}

void apm() {
    fill(muchie+1,muchie+n+1,oo);
    pq.push({0,1});
    while (pq.empty()==0) {
        int nod = pq.top().second;
        int edge = pq.top().first;
        pq.pop();
        if (!viz[nod]) {
            tot_cost += edge;
            viz[nod]=1;
            for (auto k:v[nod]) {
                if (muchie[k.first]>k.second && !viz[k.first]) {
                    muchie[k.first] = k.second;
                    tata[k.first] = nod;
                    pq.push({k.second,k.first});
                }
            }
        }
    }
}

void show() {
    g << tot_cost << '\n' << n-1 << '\n';
    for (int i=2;i<=n;i++) {
        g << i << " " << tata[i] << '\n';
    }
}

int main()
{
    read();
    apm();
    show();
    return 0;
}