Cod sursa(job #3287330)

Utilizator BucsMateMate Bucs BucsMate Data 17 martie 2025 16:26:24
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

int prim(vector<vector<pair<int, int>>> &adj, int n, vector<pair<int, int>> &mst_edges)
{
    priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq;
    vector<bool> visited(n+1, false);
    int res = 0;
    pq.push({0, {-1, 1}});

    while(!pq.empty()){
        int currNode = pq.top().second.second;
        int lastNode = pq.top().second.first;
        int cost = pq.top().first;
        pq.pop();
        if(visited[currNode]){
            continue;
        }
        visited[currNode] = true;
        mst_edges.push_back({lastNode, currNode});
        res += cost;
        for(int i = 0; i < adj[currNode].size(); i++){
            int newNode = adj[currNode][i].first;
            int add_cost = adj[currNode][i].second;
            if(!visited[newNode]){
                pq.push({add_cost, {currNode, newNode}});
            }
        }
    }
    return res;
}

int main()
{
    int n, m;
    fin >> n >> m;

    vector<vector<pair<int, int>>> adj(n+2);

    for(int i = 0; i < m; i++){
        int a, b, c;
        fin >> a >> b >> c;
        adj[a].push_back({b, c});
        adj[b].push_back({a, c});
    }
    vector<pair<int, int>> mst_edges;
    fout << prim(adj, n, mst_edges) << endl;
    fout << n-1 << endl;
    for(int i = 1; i < mst_edges.size(); i++){
        fout << mst_edges[i].first << " " << mst_edges[i].second << endl;
    }
    return 0;
}