POJ 3253(Fence Repair)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>

using namespace std;
const int maxn = 20010;
long n, len = 0;
long long  p[maxn];

void heap_insert(long long  k) {
	long t = ++len;
	p[t] = k;
	while(t>1){
		if(p[t/2] > p[t]) {
			swap(p[t], p[t/2]);
			t /= 2;
		}
		else{ break; }
	}
}

void heap_pop(){
	long t = 1;
	p[t] = p[len--];
	while( t * 2 <= len){
		long  k = t * 2;
		if(k < len && p[k] > p[k+1]){
			++k;
		}
		if(p[t] > p[k]){
			swap(p[t], p[k]);
			t = k;
		}
		else{ break; };
	}
}

int main() {
	cin >> n;
	for(int i = 1; i <= n; i++) {
		scanf("%lld", &p[i]);
		heap_insert(p[i]);
	}
	long long ans = 0;
	while(len > 1) {
		long long a, b;
		a = p[1];
		heap_pop();
		b =p[1];
		heap_pop();
		ans += a + b;
		heap_insert(a+b);
	}
	printf("%lld\n", ans);
}
//用优先队列实现起来比较容易点。


你可能感兴趣的:(POJ 3253(Fence Repair))