[C++]Fence Repair--POJ3253(优先队列)

[C++]Fence Repair(优先队列)

Fence Repair:
农夫约翰为了修理栅栏,要将一块很长的木板切割成N块。准备切成的木块的长度为L1, L2,…Ln,未切割前木板的长度恰好为切割后木板长度的总和。每次切割木板时,需要的开销为这块木板的长度。例如长度为21的木板要切成长度为5,8,8的三块木板。长21的木板切成长为13和8的木板时,开销为21.再将长度为13的板切成长度为5和8的板时,开销为13.于是合计开销时34.请求出按照目标要求将木板切割完最小的开销是多少。
输入格式:
Line 1: One integer N, the number of planks
Lines 2… N+1: Each line contains a single integer describing the length of a needed plank
输出格式:
Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts
输入:
3
8 5 8
输出:
34
解题思路:每次选择最小的两块木板相加,并将结果加入待选择木板列中,直到只剩下一块木板为止。将其放入升序优先队列中,优先队列前两位就是最小的两块木板,再将相加的结果放入优先队列中。

#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<functional>
using namespace std;

const int maxn = 10000 + 10;

int n;
priority_queue<int, vector<int>, greater<int> > que;


int main(){
	cin>>n;
	
	for(int i = 0; i<n; i++){
		int a;
		cin>>a;
		que.push(a);
	}
	
	int res = 0;
	while(que.size() > 1){
		int a = que.top();
		que.pop();
		int b = que.top();
		que.pop();
		res += (a+b);
		que.push(a+b);
	}
	
	cout<<res<<endl;
	
	return 0;
} 
发布了63 篇原创文章 · 获赞 8 · 访问量 7193

猜你喜欢

转载自blog.csdn.net/s1547156325/article/details/104498456