Cod sursa(job #3309490)

Utilizator Minea_TheodorMinea Theodor Stefan Minea_Theodor Data 5 septembrie 2025 13:39:39
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
using namespace std;
const int SIZ = 200005;
struct muchie
{
    int x, y, c;
    bool operator < (const muchie& other) const
    {
        return this->c < other.c;
    }
} v[400005];
int parent[SIZ];
int r[SIZ];
int Find(int x)
{
    if(parent[x]==x)
        return x;
    int y = Find(parent[x]);
    parent[x]=y;
    return y;
}
void Union(int a, int b)
{
    if(r[a] < r[b])
    {
        parent[a]=b;
        r[b]+=r[a];
    }
    else
    {
        parent[b]=a;
        r[a]+=r[b];
    }
}
int main()
{
    int n, m, total=0;
    cin >> n >> m;
    for(int i=1; i <= n; i++)
    {
        parent[i]=i;
        r[i]=1;
    }
    for(int i=1; i <= m; i++)
    {
        cin >> v[i].x >> v[i].y >> v[i].c;
    }
    sort(v+1, v + m + 1);
    vector<muchie> muchii;
    for(int i=1; i <= m; i++)
    {
        int a = Find(v[i].x), b = Find(v[i].y);
        if(a!=b)
        {
            total+=v[i].c;
            Union(a, b);
            muchii.push_back(v[i]);
        }
    }
    cout << total << '\n' << n-1 << '\n';
    for(auto I : muchii)
    {
        cout << I.x << " " << I.y << '\n';
    }
    return 0;
}