Cod sursa(job #2157386)

Utilizator DeleDelegeanu Alexandru Dele Data 9 martie 2018 16:32:53
Problema Arbore partial de cost minim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <vector>
#include <algorithm>
#define MAXn 200001
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct muchie{int x,y,cost; bool s;};
vector<muchie> v;
int n,m,S,nr,nmin,i;
int t[MAXn];
void citire(){
   f>>n>>m;
   muchie k;
   k.x=k.y=k.cost=-1001;
   v.push_back(k);
   for(int i=1 ; i<=m ; ++i)
   {
       f>>k.x>>k.y>>k.cost;
       v.push_back(k);
   }
}
bool cmp(muchie a,muchie b){
   return (a.cost<b.cost);
}
int tata(int x){
   if(x==t[x])
    return x;
   return t[x]=tata(t[x]);
}
int main()
{
    citire();
    sort(v.begin(),v.end(),cmp);
    for(i=1 ; i<=n ; ++i)
        t[i]=i;
    i=1;
    nr=0;
    nmin=n-1;
    while(nr<nmin)
    {
        int x=v[i].x;
        int y=v[i].y;
        x=tata(x);
        y=tata(y);
        if(x!=y)
        {
            t[y]=x;
            v[i].s=true;
            S+=v[i].cost;
            ++nr;
        }
        ++i;
    }
    g<<S<<'\n';
    g<<nmin<<'\n';
    for(i=1 ; i<=m ; ++i)
        if(v[i].s)
           g<<v[i].x<<" "<<v[i].y<<'\n';
    return 0;
}