POJ- 3253 Fence Repair

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值