Cod sursa(job #2750894)

Utilizator rares2004Ioan Rares rares2004 Data 13 mai 2021 15:37:04
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <queue>
#include <bitset>

using namespace std;

const int N = 200001;
const int M = 400001;
const int INF = 1e9;

vector <pair <int, int>> a[N];
priority_queue <pair<int, int>> pq;

int d[N], pred[N], n, m, cost;
bitset <N> selectat;

void prim_apm()
{
    for (int i = 2; i <= n; i++)
    {
        d[i] = INF;
    }
    pq.push({0, 1});
    while (!pq.empty())
    {
        int x = pq.top().second;
        pq.pop();
        if (selectat[x]) continue;
        cost += d[x];
        selectat[x] = true;
        for (auto p: a[x])
        {
            int y = p.first;
            int c = p.second;
            if (!selectat[y] && c < d[y])
            {
                d[y] = c;
                pred[y] = x;
                pq.push({-c, y});
            }
        }
    }
}

int main()
{
    ifstream in("apm.in");
    ofstream out("apm.out");
    in >> n >> m;
    for (int  i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back({y, c});
        a[y].push_back({x, c});
    }
    in.close();
    prim_apm();
    out << cost << "\n" << n - 1 << "\n";
    for (int i = 2; i <= n; i++)
    {
        out << i << " " << pred[i] << "\n";
    }
    out.close();
    return 0;
}