Cod sursa(job #3341204)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 18 februarie 2026 13:46:44
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int NMAX = 2e5 + 1;
int n, m, parent[NMAX];
bool in_mst[NMAX];
vector<pair<int, int>> adj[NMAX], mst;

int Prim()
{
    int sum = 0;
    in_mst[1] = true;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    for(auto [next, cost] : adj[1])
    {
        pq.push({cost, next});
        parent[next] = 1;
    }
    while(!pq.empty())
    {
        auto [cost, node] = pq.top(); pq.pop();
        if(in_mst[node])
            continue;
        in_mst[node] = true;
        sum += cost;
        mst.emplace_back(parent[node], node);
        for(auto [next, new_cost] : adj[node])
        {
            if(in_mst[next])
                continue;
            pq.push({new_cost, next});
            parent[next] = node;
        }
    }
    return sum;
}

int main()
{
    fin >> n >> m;
    while(m--)
    {
        int u, v, cost;
        fin >> u >> v >> cost;
        adj[u].emplace_back(v, cost);
        adj[v].emplace_back(u, cost);
    }
    fout << Prim() << "\n" << mst.size() << "\n";
    for(auto [u, v] : mst)
        fout << u << " " << v << "\n";

    fin.close();
    fout.close();
    return 0;
}