Cod sursa(job #1388111)

Utilizator GusatuMarian Gusatu Gusatu Data 15 martie 2015 10:34:40
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
#define nmax 200002
int n,i;
pair <int,int> sol[nmax];
struct muchie {
    int x,y,c;
} v[2*nmax];
int tata[nmax],m,k,cost;
int indvalmin (int i, int n)
{
    if (2*i+1<=n)
        if(v[2*i].c<v[2*i+1].c)
            return 2*i;
        else
            return 2*i+1;
    else
        return 2*i;
}
void combinare (int i, int n)
{
    int ind;
    muchie aux;
    if (i<=n/2)
        {
            ind=indvalmin(i,n);
            if (v[i].c>v[ind].c)
                {
                    aux=v[i];
                    v[i]=v[ind];
                    v[ind]=aux;
                    combinare (ind,n);
                }
        }
}
void minheap ()
{
    for (i=n/2;i>=1;i--)
        combinare(i,n);
}
int radacina(int nod) {
    if (tata[nod]==0)
        return nod;
    else {
        tata[nod]=radacina(tata[nod]);
        return tata[nod];
    }
}
void citire ()
{
    ifstream f ("apm.in");
    f>>n;
    while (f>>v[i].x>>v[i].y>>v[i].c) i++;
    m=i;
    f.close ();
}
void solve() {
    int i,tx,ty;
    for (i=1; i<=m; i++)
    {
        tx=radacina(v[i].x);
        ty=radacina(v[i].y);
        if (tx!=ty) {
            tata[tx]=ty;
            k++;
            sol[k].first=v[i].x;
            sol[k].second=v[i].y;
            cost+=v[i].c;
        }
    }
}
int main()
{
    citire ();
    minheap ();
    ofstream g ("apm.out");
    solve();
    g<<cost<<"\n"<<n-1<<"\n";
    for (int i=1; i<=k; i++)
    g<<sol[i].first<<" "<<sol[i].second<<"\n";
    g.close();
    return 0;
}