Cod sursa(job #1343781)

Utilizator SagunistuStrimbu Alexandru Sagunistu Data 15 februarie 2015 21:55:32
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
#define nmax 200005
#define cost first
#define vecin second
#define inf 0x3f3f3f3f

using namespace std;

vector<pair<int,int> >g[nmax];
priority_queue<pair<int,int> >q;
int d[nmax],n,m,viz[nmax],t[nmax];

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

void citire()
{
    fin>>n>>m;
    int x,y,c;
    for(int i=1;i<=m;i++)
    {
        fin>>x>>y>>c;
        g[x].push_back(make_pair(c,y));
        g[y].push_back(make_pair(c,x));
    }
    memset(d,inf,sizeof(d));
}

void prim()
{
    int k;
    d[1]=0;
    q.push(make_pair(0,1));
    while(!q.empty())
    {
        k=q.top().vecin;
        q.pop();
        viz[k]=1;
        vector<pair<int,int> >::iterator ii;
        for(ii=g[k].begin();ii!=g[k].end();++ii)
             if(viz[ii->vecin]==0&&d[ii->vecin]>ii->cost)
             {
                 d[ii->vecin]=ii->cost;
                 t[ii->vecin]=k;
                 q.push(make_pair(-ii->cost,ii->vecin));
             }
    }
}

void afisare()
{
    int s=0;
    for(int i=2;i<=n;i++)
        if(d[i]!=inf)
            s+=d[i];
    fout<<s<<"\n"<<n-1<<"\n";
    for(int i=2;i<=n;i++)
        fout<<i<<" "<<t[i]<<"\n";
}

int main()
{
    citire();
    prim();
    afisare();
    return 0;
}