Cod sursa(job #1698979)

Utilizator msschFMI - Enache Alexandru Madalin mssch Data 5 mai 2016 19:26:53
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

vector<int> t;
vector< pair< int, pair< int, int> > > v;
int n;

struct Comp
{
   bool operator()(pair <int, pair <int, int> > s1, pair <int, pair <int, int> > s2)
   {
       return s1.first < s2.first;
   }
};

int componente(int x)
{
    if(x == t[x])
        return x;
    else
    {
        int k = componente(t[x]);
        t[x] = k;
        return t[x];
    }
}

void Kruskal()
{
    sort(v.begin(), v.end(), Comp());
    int nr = 0, x, y, s = 0;
    vector< pair <int, int> > sol;
    t.push_back(0);

    for(int i = 1; i <= n; i++)
    {
        t.push_back(i);
    }

    for(unsigned int i = 0; i < v.size() && nr < n - 1; i++)
    {
        x = componente(v[i].second.first);
        y = componente(v[i].second.second);
        if(x != y)
        {
            nr++;
            s += v[i].first;
            sol.push_back(make_pair(v[i].second.first, v[i].second.second));
            if ( x > y )
            {
                t[y] = x;
            }
            else
            {
                t[x] = y;
            }
        }
    }

    fout << s << "\n";
    fout << sol.size() << "\n";
    for(unsigned int i = 0; i < sol.size(); i++)
    {
        fout << sol[i].first << " " << sol[i].second << "\n";
    }
}

int main()
{
    int i, m, x, y, z;

    fin >> n >> m;

    for(i = 1; i <= m; i++)
    {
        fin >> x >> y >> z;
        v.push_back(make_pair(z, make_pair(x, y)));
    }

    Kruskal();

    return 0;
}