Cod sursa(job #3215031)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 14 martie 2024 17:18:59
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>

using namespace std;

const long long max_size = 2e5 + 20, INF = 2e9 + 1;

struct str{
    int nod, cost;
    bool operator < (const str & aux) const
    {
        return cost > aux.cost;
    }
};

int d[max_size], t[max_size], uz[max_size], n, ans;
vector <pair <int, int>> mc[max_size], apm;
priority_queue <str> pq;

void prim ()
{
    d[1] = 0;
    pq.push({1, 0});
    while (!pq.empty())
    {
        int nod = pq.top().nod, val = pq.top().cost;
        pq.pop();
        if (uz[nod] == 1)
        {
            continue;
        }
        uz[nod] = 1;
        if (nod != 1)
        {
            apm.push_back({t[nod], nod});
            ans += val;
        }
        for (auto f : mc[nod])
        {
            if (d[f.first] > f.second)
            {
                d[f.first] = f.second;
                t[f.first] = nod;
                pq.push({f.first, d[f.first]});
            }
        }
    }
}

void solve ()
{
    int n, m;
    cin >> n >> m;
    while (m--)
    {
        int x, y, c;
        cin >> x >> y >> c;
        mc[x].push_back({y, c});
        mc[y].push_back({x, c});
    }
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
    }
    prim();
    cout << ans << '\n' << n - 1 << '\n';
    for (auto f : apm)
    {
        cout << f.first << " " << f.second << '\n';
    }
    cout << '\n';
}

signed main ()
{
#ifdef LOCAL
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#else
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);
#endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    long long tt;
    //cin >> tt;
    tt = 1;
    while (tt--)
    {
        solve();
    }
    return 0;
}