Cod sursa(job #1499490)

Utilizator tain1234andrei laur tain1234 Data 10 octombrie 2015 18:10:13
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <vector>
using namespace std;
int H[200250*2], c[200001], P[200001], N, cnt = 0, M, a, d, b, par[200001], cost = 0;
vector<pair<int,int>> No[200001],apm;
const int inf = (1 << 30);
void addapm(int x){
	int co;
	for (unsigned int i = 0; i < No[x].size();++i){
		int ch = No[x][i].first;
		co = No[x][i].second;
		if (co < c[ch])c[ch] = co;
		if (c[ch] == co)par[No[x][i].first] = x;
	}
}
void per(int k){
	while (k / 2 && c[H[k]] < c[H[k / 2]]){
		swap(H[k], H[k / 2]);
		swap(P[H[k]], P[H[k / 2]]);;
		k /= 2;
	}
}
void sift(int k){
	int y = 0;
	while (k != y){
		y = k;
		if (y * 2 <= cnt && c[H[k]] > c[H[y * 2]])k = y * 2;
		if (y * 2 + 1 <= cnt && c[H[k]] > c[H[y * 2 + 1]])k = y * 2 + 1;
		if (k != y){
			swap(H[k], H[y]);
			P[H[k]] = k;
			P[H[y]] = y;
		}
	}
}

void add(int x){
	H[++cnt] = x;
	P[x] = cnt;
	per(cnt);
}
int rad(){
	int x = H[1];
	swap(H[1], H[cnt]);
	swap(P[H[1]], P[H[cnt]]);
	--cnt;
	sift(1);
	P[x] = 0;
	return x;
}
int main(){
	freopen("apm.in", "r", stdin);
	freopen("apm.out", "w", stdout);
	scanf("%d%d", &N, &M);
	for (int i = 2; i <= N; ++i){
		c[i] = inf;
	}
	c[1] = 0;
	for (int i = 1; i <= M; ++i){
		scanf("%d%d%d", &a, &b, &d);
		No[a].push_back(make_pair(b, d));
		No[b].push_back(make_pair(a, d));
	}
	addapm(1);
	for (int i = 2; i <= N; ++i)
		add(i);
	for (int i = 1; i < N; ++i){
		int x = rad();
		addapm(x);
		cost += c[x];
		apm.push_back(make_pair(x, par[x]));
		for (unsigned int j = 0; j < No[x].size();++j)
			if (P[No[x][j].first])per(P[No[x][j].first]);
	}
	printf("%d\n%d\n",cost,N-1);
	for (int i = 0; i < N - 1; ++i)
		printf("%d %d\n", apm[i].first, apm[i].second);
}