Cod sursa(job #2343874)

Utilizator flee123Flee Bringa flee123 Data 14 februarie 2019 14:11:32
Problema Arbore partial de cost minim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
using namespace std;

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

struct graf{
    int nod1;
    int nod2;
    int cost;
};

int n, m, nr, father[200002], height[200002];
vector <graf> graphs;
vector <graf> solutii;

bool compare(graf a, graf b)
{
    return (a.cost < b.cost);
}
void f()
{
    int i;
    for(i = 1; i <= n; i++)
        father[i] = i;
}
int Radacina(int k)
{
    while(father[k] != k)
        k = father[k];
    return k;
}

void reunite(int a, int b)
{
    if(height[a] > height[b])
        father[b] = a;
    else
    {
        father[a] = b;
        if(height[a] == height[b])
            height[a]++;
    }
}

int main()
{
    int a, i, b;
    graf var;
    fin >> n >> m;
    f();
    while(fin >> var.nod1 >> var.nod2 >> var.cost)
        graphs.push_back(var);
    sort(graphs.begin(), graphs.end(), compare);
    i = 0;
    while(i < m)
    {
        a = Radacina(graphs[i].nod1);
        b = Radacina(graphs[i].nod2);
        if(a != b)
            solutii.push_back(graphs[i]), reunite(a, b);
        i++;
    }
    a = solutii.size();
    for(i = 0; i < a; i++)
        nr+=solutii[i].cost;
    fout << nr << '\n';
    fout << a << '\n';
    for(i = 0; i < a; i++)
        fout << solutii[i].nod1 << " " << solutii[i].nod2 << '\n';

    return 0;
}