Cod sursa(job #3164267)

Utilizator ana_valeriaAna Valeria Duguleanu ana_valeria Data 2 noiembrie 2023 16:20:00
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#define INF 1000000000
#define MAX 200000
using namespace std;
ifstream cin ("apm.in");
ofstream cout ("apm.out");
vector <pair <int, int>> graph[MAX + 10];
vector <pair <int, int>> edges;
int dist[MAX + 10];
int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        graph[x].push_back({c, y});
        graph[y].push_back({c, x});
    }
    for (int i = 2; i <= n; i++)
        dist[i] = INF;
    int node = 1, totalCost = 0;
    dist[1] = -INF;
    for (int i = 2; i <= n; i++)
    {
        for (auto it : graph[node])
        {
            int next = it.second;
            int cost = it.first;
            if (dist[next] > cost)
                dist[next] = cost;
        }
        int minDist = INF, nextNode;
        for (int j = 1; j <= n; j++)
            if (dist[j] != -INF && dist[j] < minDist)
            {
                minDist = dist[j];
                nextNode = j;
            }
        edges.push_back({node, nextNode});
        dist[nextNode] = -INF;
        node = nextNode;
        totalCost = totalCost + minDist;
    }
    cout << totalCost << '\n' << edges.size() << '\n';
    for (auto it : edges)
        cout << it.first << ' ' << it.second << '\n';
    return 0;
}