Cod sursa(job #3319918)

Utilizator androcaOprea Andrei androca Data 3 noiembrie 2025 19:43:37
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;

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

int sef[200005];
struct marg
{
    int x, y, c;
}muchii[400005];
bool cmp(marg a, marg b)
{
    return a.c < b.c;
}
int bos(int x)
{
    if(sef[x] == x)
        return x;
    return sef[x] = bos(sef[x]);
}
void uni(int x, int y)
{
    int sefx = bos(x);
    int sefy = bos(y);
    sef[sefx] = sefy;
}
bool verif(int x, int y)
{
    if(bos(x) == bos(y))
        return 1;
    return 0;
}
int main()
{
    int n, m, cost = 0;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
        fin >> muchii[i].x >> muchii[i].y >> muchii[i].c;
    sort(muchii + 1, muchii + m + 1, cmp);
    for(int i = 1; i <= n; i++)
        sef[i] = i;
    vector <int> ans;
    for(int i = 1; i <= m; i++)
    {
        int x = muchii[i].x, y = muchii[i].y, c = muchii[i].c;
        if(!verif(x, y))
        {
            uni(x, y);
            ans.push_back(i);
            cost += c;
            if(ans.size() == n - 1)
                break;
        }
    }

    fout << cost << '\n' << n - 1 << '\n';
    for (int i = 0; i < ans.size(); i++)
        fout << muchii[ans[i]].y << " " << muchii[ans[i]].x << '\n';

    return 0;
}