Cod sursa(job #2179300)

Utilizator cezinatorCezar D cezinator Data 20 martie 2018 09:07:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include<vector>
#include<algorithm>

using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct muchie{int x; int y; int c;};
int n,m,p[1000002],r[1000002],cost,componente;

vector<muchie>v;
vector<muchie>::iterator it;

vector<pair<int, int> >a;
vector<pair<int, int> >::iterator it1;

bool cond(muchie m1, muchie m2)
{
    return (m2.c>m1.c);
}

int Find(int x)
{
    if(p[x]!=x) p[x]=Find(p[x]);
    return p[x];
}

void Union1(int x, int y)
{
    int xroot, yroot;
    xroot=Find(x);
    yroot=Find(y);
    if(xroot==yroot) return;
    if(r[xroot]<r[yroot])
    { p[xroot]=yroot;
    }
    else if(r[xroot]>r[yroot])
    {
        p[yroot]=xroot;
    }
    else
    {
        p[xroot]=yroot;
        r[yroot]++;
    }
}

int Union(int x, int y)
{
    int xRoot,yRoot;
    xRoot=Find(x);
    yRoot=Find(y);
    if(xRoot==yRoot) return 0;
    if(r[xRoot]<r[yRoot])
    {
        p[xRoot]=yRoot;
        r[yRoot]+=r[xRoot];
    }
    else
    {
        p[yRoot]=xRoot;
        r[xRoot]+=r[yRoot];
    }
    componente--;
    return 0;
}

int main()
{
    f>>n>>m;
    componente=n;
    muchie aux;
    int i,x,y,c;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>c;
        aux.x=x; aux.y=y; aux.c=c;
        v.push_back(aux);
    }
    sort(v.begin(),v.end(),cond);

    for(i=1;i<=n;i++)
    {
        r[i]=1;
        p[i]=i;
    }
    for(it=v.begin();it!=v.end();++it)
    {
        int x,y,c;
        x=it->x; y=it->y; c=it->c;
        if(Find(x)!=Find(y))
        {
            cost+=c;
            a.push_back(make_pair(x,y));
            Union(x,y);
            if(componente==1) break;
        }
    }
    g<<cost<<'\n'<<a.size()<<'\n';

    for(it1=a.begin();it1!=a.end();++it1)
        g<<it1->first<<' '<<it1->second<<'\n';
    f.close();
    g.close();
    return 0;
}