Cod sursa(job #751022)

Utilizator alexdmotocMotoc Alexandru alexdmotoc Data 23 mai 2012 22:08:24
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 kb
#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;
}