Cod sursa(job #1977481)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 5 mai 2017 12:25:23
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
#define Mmax 400001
#define Nmax 200001
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct muchie
{
    int in;
    int sf;
    int cost;
};
muchie muc[Mmax];
int sol[Mmax];
inline bool cmp(const muchie &x, const muchie &y)
{
    return x.cost<y.cost;
}
int t[Nmax];
int r[Nmax];
int find(int x)
{
    int rez,y;
    rez=x;
    while(rez!=t[rez])
        rez=t[rez];
    while(x!=t[x])
    {
        y=t[x];
        t[x]=rez;
        x=y;
    }
    return rez;
}
void unite(int x, int y)
{
    if(r[x]<r[y])
        t[x]=y;
    else t[y]=x;
    if(r[x]==r[y]) r[y]++;
}
int main()
{int n,m,k,i,j,c;
f>>n>>m;
for(k=1;k<=m;k++)
    f>>muc[k].in>>muc[k].sf>>muc[k].cost;
sort(muc+1,muc+m+1,cmp);
c=0;
int sum=0;
for(i=1;i<=n;i++)
{
    t[i]=i;
    r[i]=1;
}
int A,B;
for(i=1;i<=m and c<n-1;i++)
{
    A=find(muc[i].in);
    B=find(muc[i].sf);
    if(A!=B)
    {
        sol[++c]=i;
        sum+=muc[i].cost;
        unite(A,B);
    }
}
g<<sum<<'\n'<<c<<'\n';
for(i=1;i<=c;i++)
    g<<muc[sol[i]].in<<' '<<muc[sol[i]].sf<<'\n';

    return 0;
}