Cod sursa(job #1877674)

Utilizator ifrimencoAlexandru Ifrimenco ifrimenco Data 13 februarie 2017 17:38:08
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>
#define nmax 200003
#define nmaxmuchii 400003
 using namespace std;

struct muchie{int x, y, cost;} v[nmaxmuchii]; int c[nmax], a[nmax];
bool cmp(muchie a, muchie b)
{
    return (a.cost<b.cost);

}
int main()
{
    int n, m, i, j;

  ifstream f("apm.in");
  ofstream g("apm.out");
  f >> n >> m;
  int nrmsel, cost=0;
  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<=n;++i) c[i]=i;
        nrmsel=0;

        for (i=1;nrmsel<n-1; i++)
        if (c[v[i].x]!=c[v[i].y])
        {
            cost+=v[i].cost;
            a[++nrmsel]=i;
             int mi=min(c[v[i].x],c[v[i].y]);
             int ma=max(c[v[i].x],c[v[i].y]);
             for (j=1;j<=n;++j)
                if (c[j]==ma) c[j]=mi;

        }
g << cost << "\n";
for (i=1;i<=nrmsel;++i)
g << v[a[i]].x<< " " << v[a[i]].y << "\n";
     return 0;
}