Cod sursa(job #3030211)

Utilizator Mihai7218Bratu Mihai-Alexandru Mihai7218 Data 17 martie 2023 15:56:54
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, i, j, x, y, nm, p[200001], r[200001], c, cost;
struct muchie
{
    int x, y;
    short c;
};
vector <muchie> g, sol;
int root (int x)
{
   while (r[x] != x)
        x = r[x];
    return x;
}
bool comp (muchie a, muchie b)
{
    return a.c < b.c;
}
int merger (int x, int y)
{
    if (p[x] < p[y])
        r[x] = y;
    else if (p[x] > p[y])
        r[y] = x;
    else if (p[x] == p[y])
    {
        r[y] = x;
        p[x]++;
    }
}
int main()
{
    fin >> n >> m;
    for (i = 1; i <= n; i++)
        r[i] = i;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        g.push_back({x, y, c});
    }
    sort (g.begin(), g.end(), comp);
    i = 0;
    while (nm < n-1)
    {
        x = g[i].x; y = g[i].y;
        int rx = root(x), ry = root(y);
        if (rx != ry)
        {
            merger(rx, ry);
            nm++;
            sol.push_back(g[i]);
            cost += g[i].c;
        }
        i++;
    }
    fout << cost << '\n' << n-1 << '\n';
    for (auto it : sol)
    {
        fout << it.y << ' ' << it.x << '\n';
    }
    return 0;
}