51nod-1117 聪明的木匠
2016-08-26 09:36
190 查看
原题链接
1117 聪明的木匠
题目来源: 河北大学算法艺术协会
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
收藏
关注
一位老木匠需要将一根长的木棒切成N段。每段的长度分别为L1,L2,......,LN(1 <= L1,L2,…,LN <= 1000,且均为整数)个长度单位。我们认为切割时仅在整数点处切且没有木材损失。
木匠发现,每一次切割花费的体力与该木棒的长度成正比,不妨设切割长度为1的木棒花费1单位体力。例如:若N=3,L1 = 3,L2 = 4,L3 = 5,则木棒原长为12,木匠可以有多种切法,如:先将12切成3+9.,花费12体力,再将9切成4+5,花费9体力,一共花费21体力;还可以先将12切成4+8,花费12体力,再将8切成3+5,花费8体力,一共花费20体力。显然,后者比前者更省体力。
那么,木匠至少要花费多少体力才能完成切割任务呢?
Input
Output
Input示例
Output示例
要想使花的体力达到最小那么切割木块的过程就像构建一棵哈夫曼数,数的带权路径长度就是花的体力。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define MOD 10007
#define maxn
using namespace std;
typedef long long ll;
int main(){
priority_queue<int, vector<int>, greater<int> > pq;
int n, a;
scanf("%d", &n);
while(n--){
scanf("%d", &a);
pq.push(a);
}
ll ans = 0;
while(pq.size() > 1){
int p1 = pq.top();
pq.pop();
int p2 = pq.top();
pq.pop();
ans += p1 + p2;
pq.push(p1+p2);
}
printf("%I64d\n", ans);
return 0;
}
1117 聪明的木匠
题目来源: 河北大学算法艺术协会
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
收藏
关注
一位老木匠需要将一根长的木棒切成N段。每段的长度分别为L1,L2,......,LN(1 <= L1,L2,…,LN <= 1000,且均为整数)个长度单位。我们认为切割时仅在整数点处切且没有木材损失。
木匠发现,每一次切割花费的体力与该木棒的长度成正比,不妨设切割长度为1的木棒花费1单位体力。例如:若N=3,L1 = 3,L2 = 4,L3 = 5,则木棒原长为12,木匠可以有多种切法,如:先将12切成3+9.,花费12体力,再将9切成4+5,花费9体力,一共花费21体力;还可以先将12切成4+8,花费12体力,再将8切成3+5,花费8体力,一共花费20体力。显然,后者比前者更省体力。
那么,木匠至少要花费多少体力才能完成切割任务呢?
Input
第1行:1个整数N(2 <= N <= 50000) 第2 - N + 1行:每行1个整数Li(1 <= Li <= 1000)。
Output
输出最小的体力消耗。
Input示例
3 3 4 5
Output示例
19
要想使花的体力达到最小那么切割木块的过程就像构建一棵哈夫曼数,数的带权路径长度就是花的体力。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define MOD 10007
#define maxn
using namespace std;
typedef long long ll;
int main(){
priority_queue<int, vector<int>, greater<int> > pq;
int n, a;
scanf("%d", &n);
while(n--){
scanf("%d", &a);
pq.push(a);
}
ll ans = 0;
while(pq.size() > 1){
int p1 = pq.top();
pq.pop();
int p2 = pq.top();
pq.pop();
ans += p1 + p2;
pq.push(p1+p2);
}
printf("%I64d\n", ans);
return 0;
}
相关文章推荐
- 51NOD——1117 聪明的木匠(可用优先队列解决的贪心算法)
- 51Nod-1117-聪明的木匠
- 51nod 1117 聪明的木匠 (贪心)
- 【51Nod】1117 聪明的木匠
- 【51nod】1117 聪明的木匠
- 51NOD 1117 聪明的木匠
- 51Nod 1117 聪明的木匠 (优先队列构造哈夫曼树)
- 51nod 1117 聪明的木匠
- 51nod 1117 聪明的木匠
- 51nod 1117 聪明的木匠 (优先队列_STL)
- 51nod 1117 聪明的木匠
- 51nod 1117 聪明的木匠(简单贪心)
- 51nod 1117聪明的木匠-贪心算法
- 51nod 1117 聪明的木匠(贪心)
- 51nod-【1117 聪明的木匠】
- 51nod--1117-聪明的木匠
- 51nod-1117 聪明的木匠
- 51Nod 1117 聪明的木匠(贪心+优先队列)
- 51Nod-1117-聪明的木匠
- 51nod 1117 聪明的木匠 (哈夫曼树)