Cod sursa(job #2758465)

Utilizator Vlad_PipereaPiperea Vlad Vlad_Piperea Data 10 iunie 2021 16:23:52
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

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

const int N = 200001 , INF = 1e9;

vector <pair <int, int>> a[N];
priority_queue <pair <int, int>> pq;

int d[N], pred[N] , n , m , cost;
bitset <N> selectat;

void prim_apm()
{
    for(int i = 2; i <= n; i++)
    {
        d[i] = INF;
    }
    pq.push({0, 1});
    while(!pq.empty())
    {
        int x = pq.top().second;
        pq.pop();
        if(selectat[x]) continue;
        cost += d[x];
        selectat[x] = true;
        for(auto p : a[x])
        {
            int y = p.first, c = p.second;
            if( !selectat[y] && c < d[y] )
            {
                d[y] = c, pred[y] = x;
                pq.push({-c, y});
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for( int  i = 0 ; i < m ; i++)
    {
        int x , y , c;
        in >> x >> y >> c;
        a[x].push_back({y, c});
        a[y].push_back({x, c});
    }
    prim_apm();
    out << cost << "\n" << n - 1 << "\n";
    for(int i = 2; i <= n; i++)
    {
       out << i << " " << pred[i] << "\n";
    }
    return 0;
}