Cod sursa(job #3361757)

Utilizator cont_superscoalaSuperScoala cont_superscoala Data 28 iulie 2026 12:40:40
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
/*
https://infoarena.ro/problema/apm
*/
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int INF = 2e8;

struct muchie
{
    int x, y, c;
    int celalalt(int vf)
    {
        return (x + y - vf);
    }
};

int main()
{
    ifstream in("apm.in");
    ofstream out("apm.out");
    int n, m;
    in >> n >> m;
    vector <muchie> e(m);
    vector <vector <int>> lst_a(n + 1);
    for (int i = 0; i < m; i++)
    {
        in >> e[i].x >> e[i].y >> e[i].c;
        lst_a[e[i].x].push_back(i);
        lst_a[e[i].y].push_back(i);
    }
    in.close();
    priority_queue <pair <int, int>, vector <pair <int, int>>,
                   greater <pair <int, int>>> h;
    vector <int> d(n + 1, INF);
    d[1] = 0;
    h.push({d[1], 1});
    int cost = 0;
    vector <int> vecin_apm(n + 1, 0);
    vector <bool> in_apm(n + 1, false);
    while (!h.empty())
    {
        int x = h.top().second;
        h.pop();
        if (!in_apm[x])
        {
            in_apm[x] = true;
            cost += d[x];
            for (auto i: lst_a[x])
            {
                int y = e[i].celalalt(x);
                if (!in_apm[y] && e[i].c < d[y])
                {
                    d[y] = e[i].c;
                    vecin_apm[y] = x;
                    h.push({d[y], y});
                }
            }
        }

    }
    out << cost << "\n" << n - 1 << "\n";
    for (int i = 2; i <= n; i++)
    {
        out << i << " " << vecin_apm[i] << "\n";
    }
    out.close();
    return 0;
}