Cod sursa(job #624351)

Utilizator 1994Barbulescu Daniel 1994 Data 22 octombrie 2011 11:29:44
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <cstdio>
#include <algorithm>
using namespace std;

struct nod{
    int c;
    int x,y;
}cost[400010];

struct muchie{
    int p,u;
}mu[400010];

int n,m,nrm;
int t[400010];
int ind[400010];
int costt;

bool comp(int i, int j)
{
    return (cost[i].c < cost[j].c);
}

void read()
{
    scanf("%d %d",&n,&m);
    for (int i=1;i<=m;i++)
    {
        scanf("%d %d %d",&cost[i].x,&cost[i].y,&cost[i].c);
        ind[i]=i;
    }
    sort(ind+1,ind+1+m,comp);
    for (int i=1;i<=n;i++)
        t[i]=i;
}

int f(int i)
{
    if (t[i]==i)
        return i;
    return t[i]=f(t[i]);
}

void solve()
{
    for (int i=1;i<=m;i++)
        if (f(cost[ind[i]].x)!=f(cost[ind[i]].y))
        {
            t[f(cost[ind[i]].y)]=f(cost[ind[i]].x);
            costt+=cost[ind[i]].c;
            nrm++;
            mu[nrm].p=cost[ind[i]].x;
            mu[nrm].u=cost[ind[i]].y;
        }
    printf("%d\n",costt);
}

void write()
{
    printf("%d\n",nrm);
    for (int i=1;i<=nrm;i++)
        printf("%d %d\n",mu[i].p,mu[i].u);
}

int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    read();
    solve();
    write();
    return 0;
}