浙大 PAT 甲级 1125 Chain the Ropes 优先队列 最小堆 queue_priority 贪婪算法
2019-09-05 20:58
393 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_39115541/article/details/100566994
思路很简单:每次找segments中最短的两截拿出来合成一截,然后当做一个新的segment放进去。最后只剩下一个segment时就是最终的longest rope。做法跟霍夫曼编码一模一样。
是一道比较简单的贪婪算法,因为绳子每次进行拼接都会缩短一半,所以很显然越长的越放在最后,只用拼接一次,长度也只损耗一半。
每次需要拿出最短的两截,很显然需要用到优先队列,即最小最大堆。C++的STL已经帮我们实现了priority_queue,直接使用即可。优先队列的用法,以及设置自定义比较规则,可以参考下面的博客:
https://www.geek-share.com/detail/2686467144.html
最后贴上AC代码
[code]#include<stdio.h> #include<algorithm> #include<math.h> #include<queue> #include<functional> using namespace std; int main() { priority_queue<double,vector<double>,greater<double>> segments; int N; scanf("%d", &N); for (int i = 0; i < N; i++) { int segment; scanf("%d", &segment); segments.push(segment); } while (segments.size() > 1) { double a = segments.top(); segments.pop(); double b = segments.top(); segments.pop(); double c = a / 2 + b / 2; segments.push(c); } printf("%d\n", (int)segments.top()); return 0; }
相关文章推荐
- PAT甲级——1125 Chain the Ropes (25 分)
- PAT - 甲级 - 1125. Chain the Ropes (25)
- PAT甲级 1125 - Chain the Ropes
- pat 甲1125. Chain the Ropes (贪心)
- PAT (Advanced Level) Practise 1125 Chain the Ropes (25)
- 892A. Greed#贪婪(优先队列priority_queue)
- PAT甲1125 Chain the Ropes
- PAT 1125 Chain the Ropes python解法
- PAT (Advanced Level) Practise 1125 Chain the Ropes (25)
- PAT 甲级 1003. Emergency 使用 优先队列 dijkstra 算法
- PAT 修理牧场(25)(Huffman问题,优先队列priority_queue)(与poj 3253 一模一样的思路)
- PAT (Advanced Level)-1125 Chain the Ropes
- min heap priority queue 最小堆实现的优先队列
- 优先队列priority_queue使用方法
- c++ 优先队列 priority_queue
- pat A1125 Chain the Ropes(25 分)
- queue队列容器与priority_queue优先队列容器
- Priority_queue优先队列容器
- 优先队列priority_queue 用法详解
- STL中优先队列(priority_queue)的相关操作