Cod sursa(job #2046785)

Utilizator MaligMamaliga cu smantana Malig Data 24 octombrie 2017 09:26:27
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>

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

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

int N,M;
bool inApm[NMax];
int cost[NMax];

struct elem {
    int node,dad,cost;
    elem(int _node = 0,int _dad = 0,int _cost = 0) {
        node = _node;
        dad = _dad;
        cost = _cost;
    }

    /*
    bool operator <(const elem& other) {
        return c > other.c;
    }
    //*/
};
vector<elem> sol;
vector< pair<int,int> > v[NMax];

bool operator < (const elem& a,const elem& b) {
    return a.cost > b.cost;
}

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

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

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

    int apmCost = 0;
    priority_queue< elem > Q;
    Q.push( elem(1,0,0) );
    while (Q.size()) {
        auto e = Q.top();
        Q.pop();

        int node = e.node, nodeCost = e.cost;
        if (inApm[node]) {
            continue;
        }
        apmCost += nodeCost;
        sol.pb( e );
        inApm[node] = true;

        //cout<<e.node<<' '<<e.dad<<' '<<e.cost<<'\n';

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

            cost[nxt] = nxtCost;
            Q.push( elem(nxt,node,nxtCost) );
        }
    }

    out<<apmCost<<'\n'<<N-1<<'\n';
    for (int i=1;i < sol.size();++i) {
        out<<sol[i].dad<<' '<<sol[i].node<<'\n';
    }

    in.close();out.close();
    return 0;
}