Cod sursa(job #3254910)

Utilizator axetyNistor Iulian axety Data 9 noiembrie 2024 10:17:46
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
#include <utility>
#include <set>

using namespace std;

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

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() {
    fin >> n >> m;
    for (int i=1;i<=m;i++) {
        fin >> 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});
            }
        }
    }
    fout << ctot << '\n';
    fout << res.size() << '\n'; /// cout << n-1 << '\n';
    for (auto k:res) {
        fout << k.first << " " << k.second << '\n';
    }
}