Pagini recente » Cod sursa (job #1025540) | Cod sursa (job #2842736) | Cod sursa (job #672448) | Cod sursa (job #1025535) | Cod sursa (job #751022)
Cod sursa(job #751022)
#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
#define PB push_back
#define MKP make_pair
#define INF 0x3f3f3f3f
#define maxN 200005
int N , M , cost[maxN] , ant[maxN];
vector <pair <int , int> > lista[maxN] , sol;
int H[maxN] , pozH[maxN] , dim;
void apm (int best_nod)
{
for (unsigned int i = 0 ; i < lista[best_nod].size () ; ++i)
{
int nodcur = lista[best_nod][i].first;
int costcur = lista[best_nod][i].second;
if (costcur >= cost[nodcur]) continue;
cost[nodcur] = costcur;
ant[nodcur] = best_nod;
}
}
void push (int nod)
{
int tata = nod / 2;
if (nod == 1) return;
if (cost[H[tata]] <= cost[H[nod]]) return;
swap (H[tata] , H[nod]);
swap (pozH[H[tata]] , pozH[H[nod]]);
push (pozH[H[tata]]);
}
void pop (int nod)
{
int f1 = nod * 2;
int f2 = nod * 2 + 1;
int nodmin = nod;
if (f1 <= dim && cost[H[f1]] < cost[H[nodmin]])
nodmin = f1;
if (f2 <= dim && cost[H[f2]] < cost[H[nodmin]])
nodmin = f2;
if (nodmin == nod) return;
pop (pozH[H[nodmin]]);
}
void erase (int nod)
{
swap (H[nod] , H[dim]);
swap (pozH[H[nod]] , pozH[H[dim]]);
--dim;
pop (pozH[H[nod]]);
}
int main ()
{
freopen ("apm.in" , "r" , stdin);
freopen ("apm.out" , "w" , stdout);
scanf ("%d %d" , &N , &M);
int a , b , c;
for (int i = 1 ; i <= M ; ++i)
{
scanf ("%d %d %d" , &a , &b , &c);
lista[a].PB (MKP (b , c));
lista[b].PB (MKP (a , c));
}
for (int i = 1 ; i <= N ; ++i)
cost[i] = INF;
cost[1] = 0;
apm (1);
for (int i = 2 ; i <= N ; ++i)
{
H[++dim] = i;
pozH[i] = dim;
push (dim);
}
int sol_cost = 0;
for (int t = 2 ; t <= N ; ++t)
{
int best_cost , best_nod;
best_cost = cost[H[1]];
best_nod = H[1];
erase (1);
sol_cost += best_cost;
sol.PB (MKP (ant[best_nod] , best_nod));
apm (best_nod);
for (unsigned int i = 0 ; i < lista[best_nod].size () ; ++i)
{
int nodcur = lista[best_nod][i].first;
if (pozH[nodcur])
push (pozH[nodcur]);
}
}
printf ("%d\n%d\n" , sol_cost , sol.size ());
for (unsigned int i = 0 ; i < sol.size () ; ++i)
printf ("%d %d\n" , sol[i].first , sol[i].second);
return 0;
}