Cod sursa(job #1506374)

Utilizator superstar1998Moldoveanu Vlad superstar1998 Data 20 octombrie 2015 15:54:51
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <algorithm>

using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct muchie{int x,y,c;};
int m,n,t[200001],h[200001],k,cost,sol[200001],i;
muchie a[400001];
int compare(muchie a, muchie b)
{
    return a.c<b.c;
}
bool muchie(int x, int y)
{
    int r1,r2,x1,x2,c;
    r1=x;r2=y;
    while(r1!=t[r1])r1=t[r1];
    while(r2!=t[r2])r2=t[r2];
    if(r1==r2) return false;
    while(t[x]!=r1)x1=t[x],t[x]=t[x1],x=x1;
    while(t[y]!=r2)x2=t[y],t[y]=t[x2],y=x2;
    if(h[r1]>h[r2]) t[r2]=r1,c=r1;
    else t[r1]=r2,c=r2;
    if(h[r1]==h[r2]) h[c]++;
    return true;
}
int main()
{
    f>>n>>m;
    for(int i=1;i<=n;i++)h[i]=1,t[i]=i;
    for(int i=1;i<=m;i++)f>>a[i].x>>a[i].y>>a[i].c;
    sort(a+1,a+m+1,compare);
    i=1;
    while(k<n-1)
    {
        if(muchie(a[i].x,a[i].y)) cost+=a[i].c,sol[++k]=i;
        i++;
    }
    g<<cost<<"\n"<<n-1<<"\n";
    for(int i=1;i<n;i++) g<<a[sol[i]].x<<" "<<a[sol[i]].y<<"\n";
    f.close();
    g.close();
    return 0;
}