Cod sursa(job #560259)

Utilizator APOCALYPTODragos APOCALYPTO Data 18 martie 2011 13:30:03
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
using namespace std;
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
struct nod{
    int x,y,c;
};
struct edge{
    int x,y;
};
#define pb push_back
#define nmax 200100
ofstream fout("apm.out");
nod a[nmax];
int N,M;
int t[nmax],r[nmax];
bool cmp(nod i,nod j)
{
    return i.c<j.c;
}

void init()
{
    int i;
    for(i=1;i<=N;i++)
    {
        t[i]=i;
        r[i]=1;
    }
}

int find(int x)
{
    int R,y;
    for(R=x;R!=t[R];R=t[R]);
    for(;x!=t[x];)
    {
        y=t[x];
        t[x]=R;
        x=y;
    }
    return R;
}

void unite(int x,int y)
{
    if(r[x]>r[y])
    {
        t[y]=x;
    }
    else
    {
        t[x]=y;
    }
    if(r[x]==r[y]) r[y]++;
}

void solve()
{
    sort(a+1,a+M+1,cmp);
    vector<edge> ans;
    int no=0,cst=0;
    int i;
    for(i=1;no<N-1;i++)
    {
        if(find(a[i].x)!=find(a[i].y))
        {
            no++;
            cst+=a[i].c;
            ans.pb((edge){a[i].x,a[i].y});
            unite(find(a[i].x),find(a[i].y));
        }
    }
    fout<<cst<<"\n";
    fout<<no<<"\n";
    vector<edge>::iterator it;
    for(it=ans.begin();it<ans.end();it++)
    {
        fout<<it->x<<" "<<it->y<<"\n";
    }
}

void cit()
{
    ifstream fin("apm.in");
    int i;
    fin>>N>>M;
    for(i=1;i<=M;i++)
    {
        fin>>a[i].x>>a[i].y>>a[i].c;
    }
    init();
    fin.close();
}

int main()
{
    cit();

    solve();

    fout.close();
    return 0;
}