1 条题解
-
0
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <queue> using namespace std; const int maxn = 12005; int main(void) { int n; scanf("%d",&n); priority_queue<long long,vector<long long>,greater<long long> >q; for(int i=0;i<n;i++) { long long x; scanf("%I64d",&x); q.push(x); } long long ans = 0; while(!q.empty()) { long long t1 = q.top(); q.pop(); long long t2 = q.top(); if(q.empty()) break; q.pop(); q.push(t1+t2); ans += t1+t2; } printf("%I64d\n",ans); return 0; } 这是一个经典的贪心算法问题,本质上与霍夫曼编码问题类似。农夫约翰需要将长木板切割成 N 块指定长度的小木板,每次切割的费用等于被切割木板的长度,我们需要找到总费用最小的切割策略。 关键思路:为了最小化总费用,应该每次优先切割较短的木板。因为较短的木板作为中间产物被切割的次数较少,这样可以减少总费用。 解决方案 我们可以使用最小堆(优先队列)来解决这个问题: 将所有小木板长度放入最小堆 每次从堆中取出两个最短的木板,计算它们的和作为本次切割费用 将它们的和放回堆中 重复步骤 2-3,直到堆中只剩一个元素 所有切割费用的和即为最小总费用
- 1
信息
- ID
- 2254
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者