Cod sursa(job #2867015)

Utilizator VladPislaruPislaru Vlad Rares VladPislaru Data 10 martie 2022 10:04:52
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
#define oo 5555555

using namespace std;

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

int n, m;

struct Muchie
{
    int x, y, c;
    bool operator < (const Muchie A) const
    {
        return c < A.c;
    }
}a[400005];

int t[200005];


void Union(int x, int y)
{
    t[x] = y;
}

int Find(int x)
{
    int rad = x;
    while (t[rad] != 0)
        rad = t[rad];
    int y;
    while (x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}

void Kruskal()
{
    int nrc = n, cost_min = 0;
    vector <pair <int, int> > sol;
    for (int i = 1; i <= m && nrc > 1; i++)
    {
        int x = a[i].x;
        int y = a[i].y;
        int cost = a[i].c;
        x = Find(x);
        y = Find(y);
        if (x != y)
        {
            Union(x , y);
            sol.push_back({a[i].x, a[i].y});
            nrc--;
            cost_min += cost;
        }
    }
    fout << cost_min << "\n";
    fout << sol.size() << "\n";
    for (auto i : sol)
        fout << i.first << " " << i.second << "\n";
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> a[i].x >> a[i].y >> a[i].c;
    }
    sort (a + 1, a + m + 1);
    Kruskal();
    return 0;
}