Cod sursa(job #1829322)

Utilizator ionanghelinaIonut Anghelina ionanghelina Data 14 decembrie 2016 19:43:36
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
/**
APM-uri Kruskal
**/
#include<bits/stdc++.h>
#define maxN 200005
#define maxM 400005
using namespace std;
int t[maxN],aux,n,m,x,y,c,sol,da;
pair<int,int> ans[maxN];
typedef struct tip
{
  int x,y,cost;
};
tip muchii[maxM];
bool cmp(tip a,tip b)
{
    if(a.cost<b.cost) return 1;
    return 0;
}
void update(int x,int y)
{
    while(t[x]>=0) x=t[x];
    while(t[y]>=0) y=t[y];
    if(t[x]<t[y])
    {
        t[x]+=t[y];
        t[y]=x;
    }
        else
    {
        t[y]+=t[x];
        t[x]=y;
    }
}
int rad(int x)
{
    int y=x;
    while(t[x]>=0) x=t[x];
    while(y!=x)
    {
        aux=t[y];
        t[y]=x;
        y=aux;
    }
    return x;
}
int query(int x,int y)
{
    int a=rad(x);
    int b=rad(y);
    if(a==b) return 1;
        return 0;
}
int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&x,&y,&c);
        muchii[i]={x,y,c};
    }
    sort(muchii+1,muchii+m+1,cmp);
    for(int i=1;i<=n;i++) t[i]=-1;
    for(int i=1;i<=m;i++)
    {
        x=query(muchii[i].x,muchii[i].y);
        if(!x)
        {
            sol+=muchii[i].cost;
            ans[++da]=make_pair(muchii[i].x,muchii[i].y);
            update(muchii[i].x,muchii[i].y);
        }
    }
    printf("%d\n",sol);
    for(int i=1;i<=da;i++)
    {
        printf("%d %d\n",ans[i].first,ans[i].second);
    }
    return 0;
}