Cod sursa(job #3305504)

Utilizator tibinyteCozma Tiberiu-Stefan tibinyte Data 2 august 2025 11:34:59
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct edge
{
    int x, y, c;
    bool operator<(edge a) const
    {
        return c > a.c;
    }
};
int main()
{
    int n, m;
    fin >> n >> m;
    vector<vector<pair<int, int>>> g(n + 1);
    for (int i = 1; i <= m; ++i)
    {
        int a, b, c;
        fin >> a >> b >> c;
        g[a].push_back({b, c});
        g[b].push_back({a, c});
    }
    priority_queue<edge> pq;
    for (auto [u, cost] : g[1])
    {
        pq.push({1, u, cost});
    }

    int ans = 0;
    vector<pair<int, int>> edg;
    vector<bool> vis(n + 1);
    vis[1] = true;
    for (int i = 1; i < n; ++i)
    {
        while (!pq.empty())
        {
            auto [u, v, c] = pq.top();
            if (vis[v])
            {
                pq.pop();
            }
            else
            {
                break;
            }
        }
        if (pq.empty())
        {
            fout << -1 << '\n';
            exit(0);
        }
        auto [u, v, c] = pq.top();
        edg.push_back({u, v});
        ans += c;
        vis[v] = true;
        for (auto [u, cost] : g[v])
        {
            pq.push({v, u, cost});
        }
    }
    fout << ans << '\n';
    fout << n - 1 << '\n';
    for (auto [u, v] : edg)
    {
        fout << u << ' ' << v << '\n';
    }
}