Cod sursa(job #2716842)

Utilizator AnastasiaStefanescuAnastasia Stefanescu AnastasiaStefanescu Data 5 martie 2021 19:22:56
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <math.h>
#include <set>
#include <queue>
#include <vector>

using namespace std;

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

int n, m, f[200001], pereche[200001], cost[200001];


typedef pair <int, int> pi;

priority_queue < pi, vector <pi>, greater <pi>> pq;
vector <pi> l[200001];


int main()
{
    int x, y, c, i, nod1, nod2;
    unsigned long long suma;
    
    fin >> n >> m;
    for(i=1; i<=m; i++)
        {
            fin >> x >> y >> c;
            l[x].push_back({y, c});
            l[y].push_back({x, c});
        }
    
    for (i = 1; i<= n; i++)
        cost[i] = 1e9;
    
    pq.push({0, 1});
    
    while(pq.size() > 0)
    {
        nod1 = pq.top().second;
       pq.pop();
        f[nod1] = 1;
        for (i = 0; i < l[nod1].size(); i++)
        {
            nod2 = l[nod1][i].first;
            c = l[nod1][i].second;
            if(f[nod2] == 0 && cost[nod2] > c)
            {
                cost[nod2] = c;
                pereche[nod2] = nod1;
                pq.push({cost[nod2], nod2});
            }
        }
    }
    
    suma = 0;
    for (i = 1; i<= n; i++)
        if(cost[i] < 1e9)
            suma +=cost[i];
    
    fout << suma << '\n' << n-1 << '\n';
    
    for (i = 1; i<= n; i++)
        if(pereche[i] > 0)
            fout << i << " " << pereche[i] << '\n';
    
    
}