Cod sursa(job #3214217)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 13 martie 2024 21:33:25
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;

#define pb push_back
#define mp make_pair
#define dbg(x) cout << #x << ": " << x << "\n";
using ll = long long;

const string myf = "apm";
ifstream fin(myf + ".in");
ofstream fout(myf + ".out");

int n, m;
vector<int> g[200005];
int t[200005];
using pii = pair<int, int>;
using pipii = pair<int, pii>;

vector<pipii> v;
vector<pii> vans;

int findd(int x)
{
    return (x == t[x] ? x : t[x] = findd(t[x]));
}

void unionn(int x, int y)
{

    t[y] = x;
}

int main()
{

    fin >> n >> m;

    while (m--)
    {
        int x, y, w;
        fin >> x >> y >> w;
        g[x].pb(y);
        g[y].pb(x);
        v.pb(mp(w, mp(x, y)));
    }
    for (int i = 1; i <= n; ++i)
        t[i] = i;
    int ans = 0;
    sort(v.begin(), v.end());
    for (int i = 0; i < v.size(); ++i)
    {
        int x, y;
        x = findd(v[i].second.first);
        y = findd(v[i].second.second);
        if (x != y)
        {
            ans += v[i].first;
            unionn(x, y);
            vans.pb(mp(v[i].second.first, v[i].second.second));
        }
    }
    fout << ans << '\n';
    fout << vans.size() << "\n";
    for (auto i : vans)
        fout << i.first << " " << i.second << '\n';
    fin.close();
    fout.close();
    return 0;
}