Cod sursa(job #2468958)

Utilizator Anakin1001George Giorgiu Gica Anakin1001 Data 6 octombrie 2019 12:22:32
Problema Arbore partial de cost minim Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <climits>
#define inf INT_MAX
#define DIM 200000
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int d[DIM + 1], tata[DIM + 1], x, y, c, i, n, m;
bool  viz[DIM + 1];
struct cmp{
    bool operator () (int &a, int &b){
        return d[a] > d[b];
    }
};
vector < pair < int, int > > graph[DIM + 1];
priority_queue < int , vector < int > , cmp > heap;
int main()
{   f >> n >> m;
    for( i = 1; i <= m; i++ ){
        f >> x >> y >> c;
        graph[x].push_back({y,c});
        graph[y].push_back({x,c});
    }
    for( i = 2; i  <= n; i++ )
        d[i] = inf;
    for( i = 0; i < graph[1].size(); i++ ){
        int new_node = graph[1][i].first;
        int cost = graph[1][i].second;
        d[new_node] = cost;
        tata[new_node] = 1;
        heap.push(new_node);
    }
    viz[1] = 1;
    int S = 0;
    int k = 0;
    while( !heap.empty() && k != n - 1 ){
        if(viz[heap.top()] == 1){
            heap.pop();
            continue;
        }
        int node = heap.top();
        viz[node] = 1;
        heap.pop();
        S += d[node];
        k++;
        for( int j = 0; j < graph[node].size(); j++ ){
            int new_node = graph[node][j].first;
            int cost = graph[node][j].second;
            if( d[new_node] > cost && viz[new_node] == 0){
                d[new_node] = cost;
                heap.push(new_node);
                tata[new_node] = node;
            }
        }
    }
    g << S << '\n' << n - 1 << '\n';
    for( i = 2; i <= n; i++ )
        g << i << ' ' << tata[i] << '\n';
    return 0;
}