Cod sursa(job #2714606)

Utilizator Bogdan.paun50Mandresi Bogdan Bogdan.paun50 Data 2 martie 2021 08:48:51
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

int v[200005];
int n, m, k, x1, y2, t;

struct apm
{
    int x;
    int y;
    int cost;
} a[400005], sol[200005];

bool cmp(const apm &a, const apm &b)
{
    return a.cost < b.cost;
}

int get_root(int x)
{
    while(v[x] > 0)
        x = v[x];
    return x;
}

int main()
{
    fin >> n >> m;
    k = 0;
    for(int i = 1; i <= m; i++)
        fin >> a[i].x >> a[i].y >> a[i].cost;
    sort(a+1, a+m+1, cmp);

    for(int i = 1; i <= n; i++)
        v[i] = -1;

    int i = 0;
    while(k < n-1)
    {
        i++;
        x1 = get_root(a[i].x);
        y2 = get_root(a[i].y);
        if(x1 != y2)
        {
            if(v[x1] < v[y2])
            {
                t += a[i].cost;
                k++;
                sol[k].x = a[i].x;
                sol[k].y = a[i].y;
                v[x1] += v[y2];
                v[y2] = x1;
            }
            else{
                t += a[i].cost;
                k++;
                sol[k].x = a[i].x;
                sol[k].y = a[i].y;
                v[y2] += v[x1];
                v[x1] = y2;
            }
        }
    }
    fout << t << "\n" << k << "\n";
    for(int i = 1; i <= k; i++)
        fout << sol[i].x << " " << sol[i].y << "\n";
    return 0;
}