Cod sursa(job #3337049)

Utilizator petru-robuRobu Petru petru-robu Data 26 ianuarie 2026 21:24:32
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, mst_cost;
vector<vector<pair<int, int>>> adj_list;
vector<pair<int, int>> mst;
vector<int> used, min_cost, parent;

void read()
{
    fin >> n >> m;

    adj_list.assign(n+1, {});
    used.assign(n+1, 0);
    min_cost.assign(n+1, INT_MAX);
    parent.assign(n+1, 0);

    for(int i=0; i<m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;

        adj_list[x].push_back({c, y});
        adj_list[y].push_back({c, x});
    }
}

void prim()
{
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int,int>>> pq;
    pq.push({0,1});

    while(!pq.empty())
    {
        auto [curr_cost, curr_x] = pq.top();
        pq.pop();

        if(used[curr_x])
            continue;

        used[curr_x] = 1;   

        if(curr_x != 1)
            mst.push_back({parent[curr_x], curr_x});

        mst_cost += curr_cost;

        for(auto &next:adj_list[curr_x])
        {
            auto [next_cost, next_x] = next;

            if(min_cost[next_x] > next_cost)
            {
                min_cost[next_x] = next_cost;
                pq.push({min_cost[next_x], next_x});
                parent[next_x] = curr_x;
            }
        }
    }
}

int main()
{
    read();
    prim();

    fout << mst_cost << '\n';
    fout << mst.size() << '\n';

    for(auto &edge:mst)
    {
        fout << edge.first << ' ' << edge.second << '\n';
    }
    return 0;
}