Pagini recente » Cod sursa (job #485054) | Cod sursa (job #1080502) | Cod sursa (job #2117112) | Cod sursa (job #2333851) | Cod sursa (job #2468947)
#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;
while( !heap.empty() ){
if(viz[heap.top()] == 1){
heap.pop();
continue;
}
int node = heap.top();
viz[node] = 1;
heap.pop();
S += d[node];
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;
viz[new_node] = 0;
}
}
}
// 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;
}