Cod sursa(job #2344170)

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

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

struct graf{
    int nod1, nod2, cost;
};
int n, m, father[200002], x;
graf graphs[400002], solutii[400002];

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)
{
    int r = k, y=0;
    while(father[r]!=r) r=father[r];
    while(father[k]!=k)
    {
        y=father[k];
        father[k]=r;
        k=y;
    }
    return r;
}

int main()
{
    int a, i = 1, b;
    long long y = 0;
    fin >> n >> m;
    f();
    while(fin >> graphs[i].nod1 >> graphs[i].nod2 >> graphs[i].cost)
        i++;
    sort(graphs + 1, graphs + m + 1, compare);
    i = 1;
    while(i <= m)
    {
        a = Radacina(graphs[i].nod1);
        b = Radacina(graphs[i].nod2);
        if(a != b)
            solutii[x] = graphs[i], father[a] = b, y+=graphs[i].cost, x++;
        i++;
    }
    fout << y << '\n';
    fout << x << '\n';
    for(i = 0; i < x; i++)
        fout << solutii[i].nod1 << " " << solutii[i].nod2 << '\n';
    return 0;
}