Cod sursa(job #1499470)

Utilizator tain1234andrei laur tain1234 Data 10 octombrie 2015 17:47:25
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 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 poz)
{
	while ((poz * 2 <= cnt && c[H[poz]] > c[H[poz * 2]]) || (poz * 2 + 1 <= cnt && c[H[poz]] > c[H[poz * 2 + 1]]))
	{
		if (c[H[poz * 2]] < c[H[poz * 2 + 1]] || poz * 2 + 1 > cnt)
		{
			swap(H[poz], H[poz * 2]);
			swap(P[H[poz]], P[H[poz * 2]]);
			poz *= 2;
		}
		else
		{
			swap(H[poz], H[poz * 2 + 1]);
			swap(P[H[poz]], P[H[poz * 2 + 1]]);
			poz = poz * 2 + 1;
		}
	}
}
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"<<N-1<<"\n";
	for (auto& i : apm)
		of << i.first << " " << i.second << "\n";
}