Cod sursa(job #830013)

Utilizator vendettaSalajan Razvan vendetta Data 6 decembrie 2012 10:24:19
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <set>

using namespace std;

#define nmax 200005
#define inf (1<<29)

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

int n, m, d[nmax], viz[nmax], t[nmax];
set< pair<int,int> > S;
vector< pair<int,int> > gf[nmax];

void citeste(){

    f >> n >> m;
    for(int i=1; i<=m; ++i){
        int x, y, c;
        f >> x >> y >> c;
        gf[x].push_back( make_pair(y,c) );
        gf[y].push_back( make_pair(x,c) );
    }

}


void rezolva(){

    for(int i=0; i<nmax; ++i) d[i] = inf;

    d[1] = 0;

    S.insert( make_pair(d[1], 1) );
    int s= 0;
    for(; S.size(); ){
        int nod = (*S.begin()).second;
        S.erase(S.begin());
        if (viz[nod] == 1){
            continue;
        }
        viz[nod] = 1;
        s+=d[nod];
        for(int i=0; i<gf[nod].size(); ++i){
            int vc = gf[nod][i].first;
            int cost = gf[nod][i].second;
            if (d[vc] > cost && viz[vc] == 0){
                d[vc] = cost;
                t[vc] = nod;
                S.insert( make_pair(d[vc], vc) );
            }
        }
    }

    int tot = 0;
    for(int i=1; i<=n; ++i) tot += d[i];
    //cout << tot << "\n";
    g << tot << "\n";
    //cout << n-1 << "\n";
    g << n-1 << "\n";
    for(int i=2; i<=n; ++i){
        //cout << i << " "<< t[i] << "\n";
        g << i << " "<< t[i] << "\n";
    }

}

int main(){

    citeste();
    rezolva();

    f.close();
    g.close();

    return 0;

}