Cod sursa(job #1499449)

Utilizator tain1234andrei laur tain1234 Data 10 octombrie 2015 17:27:41
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#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);
ifstream f("apm.in");
ofstream of("apm.out");
void addapm(int x){
	int co;
	for (auto& i : No[x]){
		int ch = i.first;
		co = i.second;
		if (co < c[ch])c[ch] = co;
		if (c[ch] == co)par[i.first] = x;
	}
}
void per(int k){
	while (k / 2 && c[H[k]] < c[H[k / 2]]){
		swap(H[k], H[k / 2]);
		P[H[k]] = k;
		P[H[k / 2]] = 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;
		swap(H[k], H[y]);
		P[H[k]] = k;
		P[H[y]] = y;
	}
}
void add(int x){
	++cnt;
	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(){
	f >> N >> M;
	for (int i = 2; i <= N; ++i){
		c[i] = inf;
	}
	c[1] = 0;
	for (int i = 1; i <= M; ++i){
		f >> a >> b >> d;
		No[b].push_back(make_pair(a, d));
		No[a].push_back(make_pair(b, 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 (auto& j : No[x])
			if (P[j.first])per(P[j.first]);
	}
	of << cost << "\n";
	of << apm.size() << "\n";
	for (auto& i : apm)
		of << i.first << " " << i.second << endl;
}