POJ 3253 Fence Repair
Description
Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the "kerf", the extra length lost to sawdust when a sawcut is made; you should ignore it, too.
FJ sadly realizes that he doesn't own a saw with which to cut the wood, so he mosies over to Farmer Don's Farm with this long board and politely asks if he may borrow a saw.
Farmer Don, a closet capitalist, doesn't lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.
Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.
解题报告:
明显砍的过程可以转化为合并的过程,所以考虑怎样合并最好,显然是每次选择最小的两堆合并,因为先合并的,需要贡献答案的次数越多,所以长度大的要放在最后合并,那么问题就变成了合并果子
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <cstdio>
#include <cmath>
#define RG register
#define il inline
#define iter iterator
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
const int N=2e4+5;
struct comp{
bool operator ()(int i,int j){
return i>j;
}
};
priority_queue<ll,vector<ll>,comp>q;
void work()
{
int n,x;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&x);
q.push(x);
}
ll ans=0,t1,t2;
for(int i=1;i<n;i++){
t1=q.top();q.pop();
t2=q.top();q.pop();
ans+=t1+t2;
q.push(t1+t2);
}
printf("%lld\n",ans);
}
int main()
{
work();
return 0;
}