Cod sursa(job #2641082)

Utilizator sebimihMihalache Sebastian sebimih Data 9 august 2020 21:45:34
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <limits.h>

using namespace std;

const int N = 200005;

ifstream fin("apm.in");
ofstream fout("apm.out");

vector<pair<int, int>> g[N];
bool vis[N];
int tata[N];
int n, m;

int main()
{
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        g[x].push_back({ y, c });
        g[y].push_back({ x, c });
    }

    priority_queue<pair<int, int>> heap;
    heap.push({ 0, 1 });

    int costTotal = 0;
    while (!heap.empty())
    {
        int nod = heap.top().second;
        int cost = heap.top().first;
        heap.pop();

        if (vis[nod])
            continue;

        vis[nod] = true;
        costTotal -= cost;

        for (auto y : g[nod])
        {
            if (!vis[y.first])
            {
                heap.push({ -y.second, y.first });
                tata[y.first] = nod;
            }
        }
    }

    fout << costTotal << '\n';
    fout << n - 1 << '\n';
    for (int i = 2; i <= n; i++)
    {
        fout << i << ' ' << tata[i] << '\n';
    }

    return 0;
}