Cod sursa(job #3254907)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 9 noiembrie 2024 10:15:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <vector>
#include <set>
using namespace std;

int n, m;
vector < pair < int, int > > v[1000005];
int x, y, c, ctot;
vector < pair < int, int > > res;
int dist[1000005], vec[1000005];
int inf = 1000000000;
bool viz[1000005];
set < pair < int , int > > s;

int main() {
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);
    cin >> n >> m;
    for (int i=1;i<=m;i++) {
        cin >> x >> y >> c;
        v[x].push_back({y, c});
        v[y].push_back({x, c});
    }
    for (int i=1;i<=n;i++) 
        dist[i] = inf;
    dist[1] = 0;
    s.insert({0, 1});
    while (!s.empty()) {
        int nod = s.begin()->second;
        int cost = s.begin()->first;
        viz[nod] = 1;
        s.erase(s.begin());
        ctot += cost;
        if (nod != 1) /// prima "muchie" (de la 1 la nimic practic) nu se adauga
            res.push_back({nod, vec[nod]});
        for (auto k:v[nod]) {
            if (dist[k.first] > k.second && !viz[k.first]) {
                s.erase({dist[k.first], k.first});
                dist[k.first] = k.second;
                vec[k.first] = nod;
                s.insert({dist[k.first], k.first});
            }
        }
    }
    cout << ctot << '\n';
    cout << res.size() << '\n'; /// cout << n-1 << '\n';
    for (auto k:res) {
        cout << k.first << " " << k.second << '\n';
    }
}