Cod sursa(job #2468994)

Utilizator Anakin1001George Giorgiu Gica Anakin1001 Data 6 octombrie 2019 13:17:16
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <climits>
#define inf 20000
#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 () ( pair < int , int > &a, pair < int , int > &b ) {
        return a.second > b.second;
    }
};
vector < pair < int, int > > graph[DIM + 1];
priority_queue < int , vector < pair < int , 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 = 1; i <= n; i++ )
        d[i] = inf;
    for(i = 0; i < graph[1].size(); i++ )
    {
        int node = graph[1][i].first;
        int cost = graph[1][i].second;
        d[node] = cost;
        tata[node] = 1;
        heap.push({node, cost});
    }
    viz[1] = 1;
    d[1] = 0;
    while( !heap.empty() ){
        int node = heap.top().first;
        heap.pop();
        viz[node] = 1;
        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, cost});
                tata[new_node] = node;
            }
        }
    }
    int S = 0;
    for( i = 1; i <= n; i++ )
        S += d[i];
    g << S << '\n' << n - 1 << '\n';
    for( i = 2; i <= n; i++ )
        g << i << ' ' << tata[i] << '\n';
    return 0;
}