Cod sursa(job #3329373)

Utilizator TintTint Sabei Soe Win Tint Data 13 decembrie 2025 01:26:35
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <climits>
using namespace std;

struct Edge
{
    int to, cost, from;
    bool operator>(const Edge &other) const
    {
        return cost > other.cost;
    }
};

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

    int n, m;
    fin >> n >> m;

    // Adjacency list
    vector<vector<Edge>> adj(n + 1);

    // Read edges
    for (int i = 0; i < m; i++)
    {
        int u, v, c;
        fin >> u >> v >> c;
        adj[u].push_back({v, c, u});
        adj[v].push_back({u, c, v});
    }

    // Prim's Algorithm
    vector<int> minCost(n + 1, INT_MAX);
    vector<int> parent(n + 1, -1);
    vector<bool> inMST(n + 1, false);
    priority_queue<Edge, vector<Edge>, greater<Edge>> pq;

    // Start from node 1
    minCost[1] = 0;
    pq.push({1, 0, 0});

    int totalCost = 0;
    int edgesInMST = 0;

    while (!pq.empty())
    {
        Edge current = pq.top();
        pq.pop();
        int u = current.to;

        if (inMST[u])
            continue;

        inMST[u] = true;
        totalCost += current.cost;

        if (current.from != 0)
        { // Not the starting node
            edgesInMST++;
        }

        // Update neighbors
        for (const Edge &e : adj[u])
        {
            int v = e.to;
            int cost = e.cost;

            if (!inMST[v] && cost < minCost[v])
            {
                minCost[v] = cost;
                parent[v] = u;
                pq.push({v, cost, u});
            }
        }
    }

    // Write output
    fout << totalCost << "\n";
    fout << edgesInMST << "\n";

    // Write edges (skip node 1 which has parent -1)
    for (int i = 2; i <= n; i++)
    {
        if (parent[i] != -1)
        {
            fout << parent[i] << " " << i << "\n";
        }
    }

    fin.close();
    fout.close();

    return 0;
}