Cod sursa(job #2093307)

Utilizator MaligMamaliga cu smantana Malig Data 23 decembrie 2017 13:12:34
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#if 1
#define pv(x) cout<<#x<<" = "<<x<<"; ";cout.flush()
#define pn cout<<endl
#else
#define pv(x)
#define pn
#endif

using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");

using ll = long long;
using ull = unsigned long long;
using ui = unsigned int;
#define pb push_back
#define mp make_pair
const int NMax = 2e5 + 5;
const int inf = 1e9 + 5;
const int mod = 100003;
using zint = int;

int N,M;
int cost[NMax];
bool inAPM[NMax];
vector< pair<int,int> > v[NMax];

struct muchie {
    int x,y,c;
    muchie(int _x = 0,int _y = 0,int _c = 0): x(_x), y(_y), c(_c) {}
};

struct comp {
    bool operator() (const muchie a,const muchie b) {
        return a.c > b.c;
    }
};

int main() {
    in>>N>>M;
    for (int i=1;i <= M;++i) {
        int x,y,c;
        in>>x>>y>>c;

        v[x].pb( {y,c} );
        v[y].pb( {x,c} );
    }

    for (int i=1;i <= N;++i) {
        cost[i] = inf;
    }

    vector< pair<int,int> > edges;
    int totalCost = 0;
    priority_queue<muchie,vector<muchie>,comp> pq;
    pq.push( {0,1,0} );
    cost[1] = 0;
    while (pq.size()) {
        muchie m = pq.top();
        pq.pop();
        int node = m.y;

        if (inAPM[node] || cost[node] < m.c) {
            continue;
        }
        inAPM[node] = true;
        edges.pb( {m.x,m.y} );
        totalCost += m.c;

        for (auto p : v[node]) {
            int nxt = p.first, currentCost = p.second;
            if (inAPM[nxt] || cost[nxt] <= currentCost) {
                continue;
            }

            cost[nxt] = currentCost;
            pq.push( {node,nxt,currentCost} );
        }
    }

    out<<totalCost<<'\n'<<N-1<<'\n';
    for (vector< pair<int,int> >::iterator it = edges.begin() + 1;it != edges.end();++it) {
        out<<(*it).first<<' '<<(*it).second<<'\n';
    }

    return 0;
}