Cod sursa(job #1216353)

Utilizator EpictetStamatin Cristian Epictet Data 4 august 2014 11:29:09
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
// Algoritmul lui Kruskal
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, minim, maxim, sol, C[200010];
struct Muchie { int x, y, cost; } V[400010];
vector < int > S;

inline void Citire()
{
    fin >> n >> m;
    for (int i=1; i<=m; i++)
        fin >> V[i].x >> V[i].y >> V[i].cost;
    for (int i=1; i<=n; i++) C[i] = i;
}

inline void SortareMuchii(int st, int dr)
{
    if (st < dr)
    {
        Muchie x = V[st];
        int i = st;
        int j = dr;
        while (i < j)
        {
            while (i < j && V[j].cost >= x.cost) j--;
            V[i] = V[j];
            while (i < j && V[i].cost <= x.cost) i++;
            V[j] = V[i];
        }
        V[i] = x;
        SortareMuchii(st, i-1);
        SortareMuchii(i+1, dr);
    }
}

inline int cmp(Muchie a, Muchie b)
{
    return (a.cost < b.cost);
}

int main()
{
    Citire();
    sort(V+1, V+1+m, cmp);

    for (int i=1; S.size() < n-1; i++)
    {
        if (C[V[i].x] != C[V[i].y])
        {
            S.push_back(i);
            sol += V[i].cost;
            if (C[V[i].x] < C[V[i].y])
            {
                minim = C[V[i].x];
                maxim = C[V[i].y];
            }
            else
            {
                minim = C[V[i].y];
                maxim = C[V[i].x];
            }
            for (int j=1; j<=n; j++)
                if (C[j] == maxim) C[j] = minim;
        }
    }

    fout << sol << '\n' << S.size() << '\n';
    for (int i=0; i<S.size(); i++)
        fout << V[S[i]].x << ' ' << V[S[i]].y << '\n';

    fout.close();
    return 0;
}