Cod sursa(job #2507556)

Utilizator BerescuAdrianBerescu Adrian BerescuAdrian Data 10 decembrie 2019 14:22:45
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <algorithm>
#define nmax 200001
#define mmax 400001
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int n,m,t[nmax],cost,cnt,h[nmax],sol[nmax]; //h-rang
struct muchie {int x,y,c;}v[mmax];
void citire()
{
    f>>n>>m;
    for(int i=1;i<=m;++i)
        f>>v[i].x>>v[i].y>>v[i].c;
}
int test(muchie a,muchie b)
{
    return a.c<b.c;
}
int findroot(int x)
{
    int ans=x;
    while(ans!=t[ans])
        ans=t[ans];
    int y=x;
    while(y!=ans)
    {
        int urm=t[y];
        t[y]=ans;
        y=urm;
    }
    return ans;
}
void union1(int x,int y)
{
    if(h[x]>h[y])
        t[y]=x;
    else
    {
        t[x]=y;
        if(h[x]==h[y])
            h[y]++;
    }
}
void kruskal()
{
    sort(v+1,v+m+1,test);
    for(int i=1;i<=n;++i)
        t[i]=i;
    for(int i=1;i<=m;++i)
        if(findroot(v[i].x)!=findroot(v[i].y))
        {
           union1(findroot(v[i].x),findroot(v[i].y));
             cost+=v[i].c;
             v[i].c=1002;
        }

}
int main()
{
    citire();
    kruskal();
    g<<cost<<'\n'<<n-1<<'\n';
    for(int i=1;i<=m;++i)
        if(v[i].c==1002)
          g<<v[i].x<<' '<<v[i].y<<'\n';
    return 0;
}