Cod sursa(job #3294643)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 26 aprilie 2025 17:29:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int NMAX = 2e5 + 1, INF = 2e9;
int n, m, mincost[NMAX], parent[NMAX];
bool vis[NMAX];
vector<pair<int, int>> adj[NMAX], tree;

int prim()
{
    int ans = 0;
    fill(mincost + 1, mincost + n + 1, INF);
    fill(parent + 1, parent + n + 1, -1);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, 1});
    while(!pq.empty())
    {
        int cost = pq.top().first, u = pq.top().second; pq.pop();
        if(vis[u])
            continue;
        vis[u] = true;
        ans += cost;
        if(parent[u] != -1)
            tree.push_back({parent[u], u});
        for(auto p : adj[u])
        {
            int v = p.first, weight = p.second;
            if(!vis[v] && weight < mincost[v])
            {
                mincost[v] = weight;
                parent[v] = u;
                pq.push({weight, v});
            }
        }
    }
    return ans;
}

int main()
{
    fin >> n >> m;
    while(m--)
    {
        int u, v, cost;
        fin >> u >> v >> cost;
        adj[u].push_back({v, cost});
        adj[v].push_back({u, cost});
    }
    fout << prim() << "\n" << tree.size() << "\n";
    for(auto edge : tree)
        fout << edge.first << " " << edge.second << "\n";

    return 0;
}