Cod sursa(job #2752313)

Utilizator rarestudurTudur Rares rarestudur Data 17 mai 2021 17:56:16
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

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

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

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

void prim()
 {
     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});
    }
    in.close();
    prim();
    out << cost << "\n" << n-1 << "\n";
    for(int i = 2; i <= n; i++)
    {
        out << i << " " << pred[i] << "\n";
    }
    out.close();
    return 0;
}