Cod sursa(job #2118168)

Utilizator raduzxstefanescu radu raduzx Data 30 ianuarie 2018 10:55:10
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <algorithm>
using namespace std;
#define mmax 400100
#define nmax 200010
ifstream f("apm.in");
ofstream g("apm.out");
struct muchie
{
    int x,y,cost;
};
muchie v[mmax];
int t[nmax],nivel[nmax];
bool use[mmax];
bool cmp(muchie a,muchie b)
{
    return a.cost<b.cost;
}
int father(int x)
{
    while(t[x]!=0)
        x=t[x];
    return x;
}
int w;
void adjust(int x,int y)
{
    while(t[x]!=0)
    {
        w=x;
        x=t[x];
        t[w]=y;
    }
    t[x]=y;
}
typedef long long ll;
int main()
{
    int n,m,i,tx,ty,q=0;
    ll total=0;
    f>>n>>m;
    for(i=1;i<=m;i++)
        f>>v[i].x>>v[i].y>>v[i].cost;
    sort(v+1,v+m+1,cmp);
    for(i=1;i<=m;i++)
    {
        tx=father(v[i].x);
        ty=father(v[i].y);
        if(tx!=ty)
        {
            use[i]=1;
            q+=1;
            total+=v[i].cost;
            if(nivel[tx]>nivel[ty])
                adjust(v[i].y,v[i].x);
            else
                if(nivel[tx]<nivel[ty])
                    adjust(v[i].x,v[i].y);
                else
                {
                    nivel[tx]+=1;
                    adjust(v[i].y,v[i].x);
                }
        }
    }
    g<<total<<'\n'<<q<<'\n';
    for(i=1;i<=m;i++)
        if(use[i]==1)
            g<<v[i].x<<" "<<v[i].y<<'\n';
    return 0;
}