Cod sursa(job #3324848)

Utilizator Maries_MihaiMaries Mihai Maries_Mihai Data 23 noiembrie 2025 19:08:42
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

#define nmax 200005
bool vizitat[nmax];
vector <pair<int, int>> muchii;
vector <pair<int , int>> G[nmax];
int cost;

priority_queue <pair<int, pair<int , int>>> PQ;

void prim(int n){
    for(auto it :  G[1]){
        PQ.push({-it.second, {it.first, 1}});
    }
    vizitat[1] = 1;

    int nr = 0;
    while (nr < n - 1){
        int nod = PQ.top().second.first;
        int prev = PQ.top().second.second;
        int c = -PQ.top().first;
        PQ.pop();
        if(!vizitat[nod]){
            vizitat[nod] = true;
            nr++;
            cost += c;
            muchii.push_back({nod, prev});

            for(auto it : G[nod]){
                if(!vizitat[it.first]){
                    PQ.push({-it.second, {it.first, nod}});
                }
            }
        }
    }
}
int main()
{
    int n , m;
    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});
    }

    prim(n);

    fout << cost << '\n';
    fout << n - 1 << '\n';

    for(auto it : muchii){
        fout << it.first << " " << it.second << '\n';
    }

    return 0;
}