Cod sursa(job #3215696)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 15 martie 2024 11:56:28
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define ff first
#define ss second
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define eb emplace_back
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define FORR(i, a, b) for(int i = a; i >= b; --i)
#define int long long
using namespace std;
const string TASK("apm");
ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");
#define cin fin
#define cout fout

const int N = 2e5 + 9;

int n, m;

struct info
{
    int x, y, c;

    bool operator < (info const& oth)
    {
        return c < oth.c;
    }
};
vector<info> edges;

int dsu[N], sz[N];
int find(int x){return dsu[x] == 0 ? x : dsu[x] = find(dsu[x]);}
bool unite(int x, int y)
{
    x = find(x), y = find(y);

    if(x == y)return false;

    if(sz[x] > sz[y])swap(x, y);
    dsu[x] = y;
    sz[y] += sz[x] + 1;
    return true;
}

signed main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n >> m;

    int x, y, c;
    FOR(i, 1, m)
    {
        cin >> x >> y >> c;
        edges.pb({x, y, c});
    }

    sort(edges.begin(), edges.end());
    vector<pii> arb;
    int ans = 0;
    for(auto e : edges)
        if(unite(e.x, e.y))
        {
            ans += e.c;
            arb.pb({e.x, e.y});
        }

    cout << ans << '\n';
    cout << arb.size() << '\n';
    for(auto i : arb)
        cout << i.ff << ' ' << i.ss << '\n';
    return 0;
}