代码源:844、切割

88 阅读2分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路。

logo.png

题目描述

这是代码源4月30日的div2每日一题

切割 - 题目 - Daimayuan Online Judge

有一个长度为 ∑ai 的木板,需要切割成 n 段,每段木板的长度分别为 a1,a2,…,an。

每次切割,会产生大小为被切割木板长度的开销。

请你求出将此木板切割成如上 n 段的最小开销。

输入格式

第 1 行一个正整数表示 n。

第 2 行包含 n 个正整数,即 a1,a2,…,an。

输出格式

输出一个正整数,表示最小开销。

样例输入

5
5 3 4 4 4

样例输出

47

数据范围

对于全部测试数据,满足 1≤n,ai≤10^5。

问题解析

这题可以反向考虑,即小的合成大的,每次费用是两个小的值的总和,问合成一个所需要的能量最少是多少。(不用选相邻的,不是合并石子问题)

那我们就每次选最小的两个放一起即可,贪心做法,这样每次合成所要的能量肯定是最少的。所以我们可以用一个数据结构每次把最小的两个木板找出来,把他们两个合成后再放回去,继续下一步操作,直到只剩一个木板为止。这个数据结构可以用set,map或优先队列等自己带有排序功能的(但注意set和map会去重),也可以自己写一个线段树找区间最小值,这里为方便我选的是优先队列。

AC代码

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include<numeric>
#include<string>
#include<string.h>
#include<iterator>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
#include<queue>
#include<iomanip>

#define endl '\n';
typedef long long ll;
typedef pair<ll, ll>PII;
const int N = 1e6;

inline int read() {
    int x = 0; char ch = getchar();
    while (ch < '0' || ch > '9') ch = getchar();
    while (ch >= '0' && ch <= '9') x = (x << 3) + (x << 1) + ch - '0', ch = getchar();
    return x;
}

inline void write(long long x) {
    if (x > 9) write(x / 10);
    putchar(x % 10 | '0');
}

int main()
{
    int n;
    n = read();
    vector<ll>v(n);
    priority_queue<ll,vector<ll>,greater<ll>>que;
    for (int i = 0; i < n; i++)
    {
        v[i] = read();
        que.push(v[i]);
    }
    ll res = 0;
    while (que.size() != 1)
    {
        ll ans = 0;
        ans += que.top();
        que.pop();
        ans += que.top();
        que.pop();
        res += ans;
        que.push(ans);
    }
    write(res);
    return 0;
}