Cod sursa(job #2551877)

Utilizator Robys01Robert Sorete Robys01 Data 20 februarie 2020 11:59:36
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
#include <tuple>
#define NMAX 200001
#define MMAX 400001
using namespace std;

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


vector <tuple <int, int, int> > v;
int n, m, TT[NMAX], RG[NMAX];
int nr, suma;
vector < pair <int, int> > sol;

void citire()
{
    fin>>n>>m;
    for(int i=1; i<=m; i++)
    {
        int x, y, c;
        fin>>x>>y>>c;
        v.push_back(make_tuple(c, x, y));
    }
    sort(v.begin(), v.end());

    for(int i=1; i<=n; i++)
    {
        TT[i] = i;
        RG[i] = 1;
    }
}

int Find(int x)
{
    for(; x != TT[x]; x = TT[x]);
    return x;
}

void Unite(int x, int y)
{
    if(RG[x] < RG[y])
    {
        TT[x] = TT[y];
        RG[y]+= RG[x];
    }
    else
    {
        TT[y] = TT[x];
        RG[x]+= RG[y];
    }

}

void rezolvare(){
    for(int i=0; nr<n-1; i++)
    {
        int e1, e2, cost;
        tie(cost, e1, e2) = v[i];
        int x = Find(e1), y = Find(e2);

        if(x!= y)
        {
            Unite(x, y);
            nr++; suma+=cost;
            sol.push_back(make_pair(e1, e2));
        }
    }

}

int main()
{
    citire();
    rezolvare();
    fout<<suma<<'\n'<<nr<<'\n';
    for(auto a: sol)
        fout<<a.first<<' '<<a.second<<'\n';

    return 0;
}