Cod sursa(job #2752326)

Utilizator Tudor_1808Tudor Ioan Popescu Tudor_1808 Data 17 mai 2021 18:12:31
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

const int INF = 1e9;
const int N = 200005;

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

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

int n, m, d[N], cost, pred[N];

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;
            int 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=1; 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;
}