Cod sursa(job #1994260)

Utilizator tanasaradutanasaradu tanasaradu Data 24 iunie 2017 14:59:34
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define nmax 200001
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n,m,t[nmax];
struct Graf
{
    int x,y,val,reset;
};
Graf a[nmax];
inline void Union(int x,int y)
{
    t[y]=x;
}
inline int Find(int x)
{
    int y,rad;
    rad=x;
    while(t[rad])
        rad=t[rad];
    while(x!=rad)
    {
        y=t[x];
        t[x]=rad;
        x=y;
    }
    return x;
}
void Citire()
{
    int i;
    fin>>n>>m;
    for(i=1;i<=m;i++)
        fin>>a[i].x>>a[i].y>>a[i].val;
}
inline bool Sortare(const Graf A,const Graf B)
{
    return A.val<B.val;
}
void Rezolvare()
{
    int i,x,y,cost=0;
    sort(a+1,a+m+1,Sortare);
    for(i=1;i<=m;i++)
    {
        x=Find(a[i].x);
        y=Find(a[i].y);
        if(x!=y)///nu exista cicluri
        {
            Union(x,y);
            a[i].reset=1;
            cost+=a[i].val;
        }
    }
    fout<<cost<<"\n"<<n-1<<"\n";
    for(i=1;i<=m;i++)
        if(a[i].reset==1)
            fout<<a[i].x<<" "<<a[i].y<<"\n";
}
int main()
{
    Citire();
    Rezolvare();
    fin.close();
    fout.close();
    return 0;
}