[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;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章