Cod sursa(job #2936330)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 8 noiembrie 2022 17:26:45
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

vector<pair<int, int>> g[200005];
int n,m, v[200005];

int main() {
    fin >> n >> m;
    while(m--) {
        int x, y, c;
        fin >> x >> y >> c;
        g[x].push_back({y, c});
        g[y].push_back({x, c});
    }

    priority_queue<pair<int, pair<int, int>>> pq;
    vector<pair<int, int>> ans;
    int cost = 0;
    for(auto x: g[1]) pq.push({-x.second, {1, x.first}});
    v[1] = 1;

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

        if(v[y]) continue;
        v[y] = 1;
        ans.push_back({x, y});
        cost += c;

        for(auto next: g[y]) {
            if(!v[next.first])  {
                pq.push({-next.second, {y, next.first}});
            }
        }
    }
    fout << cost << '\n' << ans.size() << '\n';
    for(auto p: ans) fout << p.first << ' ' << p.second << '\n';
}