3253 Fence Repair
Input 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
Output Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts
Sample Input
3 8 5 8
Sample Output
34
Hint He wants to cut a board of length 21 into pieces of lengths 8, 5, and 8. The original board measures 8+5+8=21. The first cut will cost 21, and should be used to cut the board into pieces measuring 13 and 8. The second cut will cost 13, and should be used to cut the 13 into 8 and 5. This would cost 21+13=34. If the 21 was cut into 16 and 5 instead, the second cut would cost 16 for a total of 37 (which is more than 34).
思路一: 用哈夫曼树的建立,然后求非叶子结点的和
思路二: 用优先队列,每次出队两个数字相加,再把该数字入队。进而求和
方便起见可以直接用优先队列解决
注意一点,就是题目说要重复输入多次,不是一次就结束。所以要用一个while循环。
#include<iostream>
#include<queue>
using namespace std;
int n,a;
priority_queue<int ,vector<int>, greater<int> >q;
void solve()
{
long long int s=0;
int s1,s2;
while(q.size()!=1)
{
s1=q.top();
q.pop();
s2=q.top();
q.pop();
int l=s1+s2;
s=s+l;
q.push(l);
}
cout<<s<<endl;
q.pop();
}
int main()
{
while(cin>>n)
{
if(n==1)
{
cin>>a;
cout<<a<<endl;
continue;
}
while(n--)
{
cin>>a;
q.push(a);
}
solve();
}
return 0;
}
|