Cod sursa(job #2507531)

Utilizator BerescuAdrianBerescu Adrian BerescuAdrian Data 10 decembrie 2019 13:48:03
Problema Arbore partial de cost minim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 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,conex[nmax],cost,cnt;
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;
    for(int i=1;i<=n;++i)
        conex[i]=i;
}
int test(muchie a,muchie b)
{
    return a.c<b.c;
}
void kruskal()
{
    sort(v+1,v+m+1,test);
    int k=1;
    while(cnt<n-1)
    {
        if(conex[v[k].x]!=conex[v[k].y])
        {
            cnt++;
            cost+=v[k].c;
            v[k].c=-1;
            int x,y;
            x=conex[v[k].y];
            y=conex[v[k].x];
            for(int j=1;j<=n;++j)
                if(conex[j]==x)
                   conex[j]=y;
        }
        k++;
    }
}
int main()
{
    citire();
    kruskal();
    g<<cost<<'\n'<<cnt<<'\n';
    for(int i=1;i<=m;++i)
        if(v[i].c==-1)
          g<<v[i].x<<' '<<v[i].y<<'\n';
    return 0;
}