Cod sursa(job #3268362)

Utilizator iccjocIoan CHELARU iccjoc Data 14 ianuarie 2025 18:36:19
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>
using namespace std;
vector<int> tati;
vector<int> heig;
void init(int n)
{
    tati.push_back(0);
    heig.push_back(0);
    for(int i = 1; i <= n; i++)
    {
        tati.push_back(i);
        heig.push_back(1);
    }
}
int query(int node)
{
    int tn = node;
    while(tn != tati[tn])
        tn = tati[tn];
    int tnn = node;
    while(tnn != tati[tnn])
    {
        int ax = tnn;
        tnn = tati[tnn];
        tati[ax] = tn;
    }
    return tn;
}
void join(int node1, int node2)
{
    node1 = query(node1);
    node2 = query(node2);
    if(heig[node1] < heig[node2])
    {
        tati[node1] = node2;
    }
    else if(heig[node1] == heig[node2])
    {
        tati[node2] = node1;
        heig[node1]++;
    }
    else
    {
        tati[node2] = node1;
    }
}
int main()
{
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    vector<pair<int, pair<int, int>>> v(m);
    for(int i = 0; i < m; i++)
    {
        cin >> v[i].second.first >> v[i].second.second >> v[i].first;
    }
    sort(v.begin(), v.end());
    init(n);
    vector<pair<int, int>> ans;
    int cost = 0;
    for(auto it = v.begin(); it != v.end(); it++)
    {
        if(query(it->second.first) != query(it->second.second))
        {
            join(it->second.first, it->second.second);
            ans.push_back(it->second);
            cost += it->first;
        }
    }
    cout << cost << "\n" << n-1 << "\n";
    for(auto it = ans.begin(); it != ans.end(); it++)
    {
        cout << it->second << " " << it->first << "\n";
    }
}