Cod sursa(job #2170487)

Utilizator victorobamavictor olaru victorobama Data 15 martie 2018 02:10:23
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int fathers[200002];
int sola[400005],solb[400005];

int find(int x)
{
    if(fathers[x]==x){return x;}
    return find(fathers[x]);
}
void unite(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    fathers[fx]=fy;
}
int main()
{

    int n,m;
        int a,b,w;

        f>>n>>m;
    for(int i=1;i<=n;i++)
        fathers[i]=i;

        vector <  pair  < int  , pair < int, int > > > edges ;


    for(int i=0;i<m;i++)
    {
        f>>a>>b>>w;
        edges.push_back(make_pair(w,make_pair(a,b)));

    }
    int mst_weight=0,mst_edges=0;
    int mst_ni=0;

    sort(edges.begin(),edges.end());

    while( mst_edges <  n-1 )
    {
        a=edges[mst_ni].second.first;
        b=edges[mst_ni].second.second;
        w=edges[mst_ni].first;

        if(find(a)!=find(b))
        {
            unite(a,b);
            mst_weight+=w;
            mst_edges++;
            sola[mst_edges]=a;
            solb[mst_edges]=b;

        }
        mst_ni++;
    }

    g<<mst_weight<<'\n';
    g<<mst_edges<<'\n';
    for(int i=1;i<=mst_edges;i++)
        g<<sola[i]<<' '<<solb[i]<<'\n';

    f.close();g.close();return 0;
    return 0;
}