您的位置:首页 > Web前端

POJ3253《Fence Repair》方法:优先队列

2013-04-09 10:27 274 查看
题目大意:需要切成20000块木块,每切一次的费用就等于该模板长度。

解题思路:因此首先将待切木板排序,每次取2块最小的木板,比如有8, 5, 8三块木板,首先切21的木板,然后切5,再切8,21+5+8=34。反过来就是5, 8, 8,第一次5+8=13, 8,13,第二次8+13=21。和为13+21=34。将这些小块木板合起来的最小费用等于将大块木板分割的最小费用。

// 480k 49ms
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

class cmp {
public:
	bool operator()(const __int64 a, const __int64 b) const {
		return a > b;
	}
};

int main()
{
	freopen("temp.txt", "r", stdin);
	int n;
	while (cin >> n) {
		priority_queue<__int64, vector<__int64>, cmp> Queue;

		for (int i = 1; i <= n; ++i) {
			__int64 tmp;
			scanf("%I64d", &tmp);
			Queue.push(tmp);
		}

		__int64 mincost = 0;
		while (Queue.size() > 1) {
			__int64 a = Queue.top();
			Queue.pop();
			__int64 b = Queue.top();
			Queue.pop();
			Queue.push(a+b);
			mincost += a+b;
		}

		printf("%I64d\n", mincost);
		
		while (!Queue.empty()) {
			Queue.pop();
		}
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: