Cod sursa(job #2816485)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 11 decembrie 2021 14:09:50
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;

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

struct muchie
{
    int x, y, c;
} v[400001];

bool comp (muchie a, muchie b)
{
    return a.c < b.c;
}

int t[200001], nr[200001];
//la inceput, nr[i] = 1, pentru orice i

void uneste (int x, int y)
{
    if (nr[x] < nr[y])
    {
        t[x] = y;
        nr[y] = nr[y] + nr[x];
    }
    else
    {
        t[y] = x;
        nr[x] = nr[x] + nr[y];
    }
}

int cauta_radacina (int x)
{
    int r, y;
    r = x;
    while (t[r] != 0)
        r = t[r];

    while (x != r)
    {
        y = t[x];
        t[x] = r;
        x = y;
    }
    return r;
}

int sol[200001];

int main()
{
    int n, m, i, rx, ry, nrsol;
    int rasp;

    fin >> n >> m;
    for (i = 1; i<=m; i++)
        fin >> v[i].x >> v[i].y >> v[i].c;
    sort(v+1, v+m+1, comp);

    for (i = 1; i<=n; i++)
        nr[i] = 1;
    rasp = 0; //rasp = costul final/ costul APM-ului
    nrsol = 0;

    for (i = 1; i<=m; i++)
    {
        rx = cauta_radacina (v[i].x);
        ry = cauta_radacina (v[i].y);
        if (rx != ry)
        {
            nrsol++;
            sol[nrsol] = i;

            rasp = rasp + v[i].c;
            uneste (rx, ry);
        }
    }
    fout << rasp << '\n';
    fout << n - 1 << '\n';
    for (i = 1; i<n; i++)
        fout << v[sol[i]].x << ' ' << v[sol[i]].y << '\n';
    return 0;
}