Cod sursa(job #1499563)

Utilizator tain1234andrei laur tain1234 Data 10 octombrie 2015 19:49:37
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <vector>
#include <bitset>
using namespace std;
int H[200001], c[200001], P[200001], N, cnt = 0, M, par[200001], cost = 0;
bitset<200001> v;
vector<pair<int,int>> No[200001];
const int inf = (1 << 30);
void swap1(int& a, int& b){
	a ^= b;
	b ^= a;
	a ^= b;
}
void per(int k){
	if (k > 1){
		int f = k >> 1;
		if (c[H[f]] > c[H[k]]){
			swap1(H[k], H[f]);
			swap1(P[H[k]], P[H[f]]);
			per(f);
		}
	}
}
void sift(int poz)
{
	int f;
	if (poz <= cnt / 2){
		if (poz*2+1<=cnt)
			if (c[H[poz * 2]] < c[H[poz * 2 + 1]])
				f = 2 * poz;
			else f = 2 * poz + 1;
		else f = 2 * poz;
		if (c[H[poz]]>c[H[f]]){
			swap1(H[poz], H[f]);
			swap1(P[H[poz]], P[H[f]]);
			sift(f);
		}
	}
}

void add(int x){
	H[++cnt] = x;
	P[x] = cnt;
	per(cnt);
}
int rad(){
	int x = H[1];
	swap1(H[1], H[cnt]);
	swap1(P[H[1]], P[H[cnt]]);
	--cnt;
	sift(1);
	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){
		int a, b, d;
		scanf("%d%d%d", &a, &b, &d);
		No[a].push_back(make_pair(b, d));
		No[b].push_back(make_pair(a, d));
	}
	add(1);
	while (cnt!=0){
		int x = rad();
		v[x] = 1;
		cost += c[x];
		for (auto& i : No[x]){
			if (!v[i.first] && i.second < c[i.first]){
				c[i.first] = i.second;
				par[i.first] = x;
				if (!P[i.first])add(i.first);
				else per(P[i.first]);
			}
		}
	}
	printf("%d\n%d\n",cost,N-1);
	for (int i = 2; i <= N; ++i)
		printf("%d %d\n", par[i],i);
}