Cod sursa(job #1653384)

Utilizator tudormaximTudor Maxim tudormaxim Data 15 martie 2016 22:27:36
Problema Arbore partial de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int nmax = 200005;
const int oo = 0x3f3f3f;
vector <pair<int,int> > g[nmax], apm;
int n, m, dist[nmax], dady[nmax];
bitset <nmax> viz;

void prim(int start)
{
    priority_queue <pair<int,int> > heap;
    vector <pair<int,int> > :: iterator it;
    int dad, son, cost, i;
    for(i=1; i<=n; i++)
        dist[i]=oo;
    dist[start]=0;
    heap.push(make_pair(0, start));
    for(i=1; i<=n; i++)
    {
        dad=heap.top().second;
        cost=-heap.top().first;
        viz[dad]=true;
        heap.pop();
        if(cost <= dist[dad])
            for(it=g[dad].begin(); it!=g[dad].end(); it++)
            {
                son=it->first;
                cost=it->second;
                if(viz[son]==false && dist[son] > cost)
                {
                    dist[son]=cost;
                    dady[son]=dad;
                    heap.push(make_pair(-dist[son], son));
                }
            }
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    int i, x, y, c, sum=0;
    fin >> n >> m;
    for(i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        g[x].push_back(make_pair(y, c));
        g[y].push_back(make_pair(x, c));
    }
    prim(1);
    for(i=1; i<=n; i++)
        sum+=dist[i];
    fout << sum << "\n" << n-1 << "\n";
    for(i=2; i<=n; i++)
        fout << i << " " << dady[i] << "\n";
    fin.close();
    fout.close();
    return 0;
}