Time Limit: 2000MS |
|
Memory Limit: 65536K |
Total Submissions: 34063 |
|
Accepted: 10969 |
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.
Input
Output
Sample Input
3
8
5
8
Sample Output
34
Hint
题意:一根木板要锯成n块,长度分别为a1,a2,a3..... 未切割的木板长度等于切割结束的长度之和。 每次切开木板时的花费等于这块木板的长度。问切完这段木板的最少总花销是多少。
题解:这里用到了霍夫曼树的思想,最短的板应当是深度最大的叶子节点之一,满足贪心思想,则次最短的板与其在二叉树中是兄弟节点。 现在将木板按照长度大小排序,则对于a1与a2,它们是由木板(a1+a2)切割而来的。并将其当做最后切割的。 所以在在此之前就有:
(a1+a2),a3,a4.....an
这样就有n-1块木板存在。重复上面求解方法,直到只剩下一块木板。
代码如下:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int a[20020]; int main() { int n,i; long long ans; while(scanf("%d",&n)!=EOF) { for(i=0;i<n;++i) scanf("%d",&a[i]); ans=0; while(n>1) { int one=0,tow=1;//one标记最小的,tow标记次最小的 int t; if(a[one]>a[tow]) { t=one; one=tow; tow=t; } for(i=2;i<n;++i) { if(a[i]<a[one]) { tow=one; one=i; } else if(a[i]<a[tow]) tow=i; } a[one]+=a[tow]; ans+=a[one]; a[tow]=a[n-1]; n--; } printf("%lld\n",ans); } return 0; }
优先队列写法,思想霍夫曼树是一样的,优先队列更加简单,时间也更短,代码如下:
#include<cstdio> #include<cstring> #include<queue> using namespace std; int main() { int n,a,one,tow,i; long long ans; while(scanf("%d",&n)!=EOF) { priority_queue<int,vector<int>,greater<int> >q; ans=0; for(i=0;i<n;++i) { scanf("%d",&a); q.push(a); } while(q.size()>1) { one=q.top(); q.pop(); tow=q.top(); q.pop(); ans+=(one+tow); q.push(one+tow); } printf("%lld\n",ans); } return 0; }