Cod sursa(job #3292892)

Utilizator rapidu36Victor Manz rapidu36 Data 9 aprilie 2025 18:00:46
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int INF = 1e9;

struct succesor
{
    int vf, c;
};

int prim(int n, vector < vector<succesor>> &s, vector <pair <int, int>> &e)
{
    vector <int> d(n + 1, INF);
    vector <int> pred(n + 1, 0);
    vector <bool> sel(n + 1, false);
    priority_queue < pair <int, int>, vector <pair <int, int>>, greater <pair <int, int>>> h;
    int cost = 0;
    d[1] = 0;
    h.push({0, 1});
    int nr_e = 0;
    while (!h.empty())
    {
        pair <int, int> p = h.top();
        h.pop();
        int c = p.first, x = p.second;
        if (sel[x])
        {
            continue;
        }
        sel[x] = true;
        if (x != 1)
        {
            e[nr_e++] = {pred[x], x};
            cost += c;
        }
        for (auto p_s: s[x])
        {
            int y = p_s.vf;
            int c = p_s.c;
            if (!sel[y] && c < d[y])
            {
                d[y] = c;
                pred[y] = x;
                h.push({d[y], y});
            }
        }
    }
    return cost;
}


int main()
{
    ifstream in("apm.in");
    ofstream out("apm.out");
    int n, m;
    in >> n >> m;
    vector <vector <succesor>> s(n + 1);
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        s[x].push_back((succesor){y, c});
        s[y].push_back((succesor){x, c});
    }
    vector <pair <int, int>> muchii_apm(n - 1);
    int cost_total = prim(n, s, muchii_apm);
    out << cost_total << "\n" << n - 1 << "\n";
    for (auto e: muchii_apm)
    {
        out << e.first << " " << e.second << "\n";
    }
    in.close();
    out.close();
    return 0;
}