复习算法至贪心法应用的最佳合并模式,其本质上解决方法就是建造一颗哈夫曼树,题解即为哈夫曼树的所有叶节点的带权路径长度之和(wpl)。该题较为容易理解。
为了巩固所学算法,特寻找了一题练手, POJ3253-Fence Repair。题目如下:
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 38302 | Accepted: 12450 |
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
Lines 2.. N+1: Each line contains a single integer describing the length of a needed plank
Output
Sample Input
3 8 5 8
Sample Output
34
Hint
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).
#include<stdio.h>
#include<vector>
#include<queue>
using namespace std;
//定义cmp类 类似于sort函数中定义的cmp函数 此题并没有用到 纯属优先权队列尝试 直接使用greater即可
class cmp
{
public:
bool operator()(const __int64 a,const __int64 b)const
{
return a>b;
}
};
int main()
{
int n;
while(scanf("%d",&n)!=EOF)//能用scanf就不要用cin 将cin更改为scanf后 时间由47ms降低至17ms
{
priority_queue<__int64, vector<__int64>, greater<__int64> > q;
//其中的greater若不写的话 则优先权最大的是最大元素 写了greater后 优先权最大的是最小元素
//优先权队列有机会的话会再详细探索
__int64 len;
for(int i=0; i<n; i++)
{
scanf("%I64d",&len); //由于结果范围可能很大 采用__int64
q.push(len); //输入要求的木板长度(费用)并入队
}
__int64 mincost=0; //最小费用
while(q.size()>1)//当队列中小于等于一个元素时跳出
{
__int64 a=q.top(); //得到队首元素的值,并使其出队 即最小元素
q.pop();
__int64 b=q.top(); //两次取队首,即得到最小的两个值 即次小元素
q.pop();
mincost+=a+b;
q.push(a+b); //入队 将最小和次小元素的和入队列
}
printf("%I64d\n",mincost);
while(!q.empty()) //清空队列
q.pop();
}
}
代码使用了优先权队列,若不使用优先权队列而是保存在一般队列的话,每次进队列都需要进行排序,会导致时间超出。看来c++STL中还是有很多很方便的函数方法的,有必要熟练掌握。另外优先队列的排序结构体找个时间好好探讨一下。