Cod sursa(job #3252801)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 31 octombrie 2024 11:21:06
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

const int NMAX = 1e5;
const int INF = 1e9;
int d[NMAX + 1];
vector<pair<int, int>> G[NMAX + 1];
int vis[NMAX + 1];
int p[NMAX + 1];

int main()
{
    ifstream f("apm.in");
    ofstream g("apm.out");
    int n, m;
    f >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        G[x].push_back({y, c});
        G[y].push_back({x, c});
    }
    for(int i = 1; i <= n; i++) {
        d[i] = INF;
    }
    d[1] = 0;
    int sum = 0;
    for(int i = 1; i <= n; i++) {
        int minim = INF;
        int node = 0;
        for(int j = 1; j <= n; j++) {
            if(d[j] < minim && !vis[j]) {
                minim = d[j];
                node = j;
            }
        }
        vis[node] = 1;
        sum += minim;
        for(auto it : G[node]) {
            if(d[it.first] > it.second && !vis[it.first]) {
                d[it.first] = it.second;
                p[it.first] = node;
            }
        }
    }
    g << sum << '\n';
    g << n - 1 << '\n';
    for(int i = 2; i <= n; i++) {
        g << i << ' ' << p[i] << '\n';
    }
    return 0;
}