Cod sursa(job #1436002)

Utilizator maricasorinSorin-Gabriel maricasorin Data 14 mai 2015 21:19:46
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>

using namespace std;

int *t;

struct triplu
{
    int a,b,cost;
};

bool comp (triplu i,triplu j) { return (i.cost<j.cost); }

int find_set(int &x)
{
    return t[x] ? t[x]=find_set(t[x]) : x;
}

int main()
{
    int n,m,cost=0;
    vector <pair<int,int> > muchii;
    vector <triplu> v;
    ifstream f("apm.in");
    f>>n>>m;
    triplu x;
    for (int i=0;i<m;i++)
    {
        f>>x.a>>x.b>>x.cost;
        v.push_back(x);
    }
    sort(v.begin(),v.end(),comp);
    t=new int[n+1];
    for (register int i=1;i<=n;i++) t[i]=0;
    for (register int i=0;i<m && muchii.size()<n-1;i++)
    {
        if (find_set(v[i].a)!=find_set(v[i].b))
        {
        t[find_set(v[i].a)]=find_set(v[i].b);
        muchii.push_back(make_pair(v[i].a,v[i].b));
        cost+=v[i].cost;
        }
    }
    ofstream g("apm.out");
    g<<cost<<endl<<n-1<<endl;
    for (register unsigned int i=0;i<muchii.size();i++) g<<muchii[i].first<<" "<<muchii[i].second<<endl;
    return 0;
}