题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1023
基准时间限制:2 秒 空间限制:131072 KB 分值: 320
难度:7级算法题
N堆石子摆成一条线。现要将石子有次序地合并成一堆。规定每次只能选相邻的2堆石子合并成新的一堆,并将新的一堆石子数记为该次合并的代价。计算将N堆石子合并成一堆的最小代价。
例如: 1 2 3 4,有不少合并方法
1 2 3 4 => 3 3 4(3) => 6 4(9) => 10(19)
1 2 3 4 => 1 5 4(5) => 1 9(14) => 10(24)
1 2 3 4 => 1 2 7(7) => 3 7(10) => 10(20)
括号里面为总代价可以看出,第一种方法的代价最低,现在给出n堆石子的数量,计算最小合并代价。
Input
第1行:N(2 <= N <= 50000) 第2 - N + 1:N堆石子的数量(1 <= A[i] <= 10000)
Output
输出最小合并代价
Input示例
4 1 2 3 4
Output示例
19
解析:这个题和V1一样,只不过范围变大了,GarsiaWachs算法复杂度O(n*log(n))
GarsiaWachs算法借鉴博客:http://blog.csdn.net/acdreamers/article/details/18043897
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 100009;
int a[N], t;
LL ans;
void Union(int k)
{
int tp = a[k] + a[k-1];
ans += tp;
a[k] = a[k+1];
t--;
int i;
for(i = k - 1; i >= 2 && a[i-1] < tp; i--) a[i] = a[i-1];
a[i] = tp;
while(i >= 3 && a[i] >= a[i-2])
{
int d = t - i;
Union(i-1);
i = t - d;
}
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
t = 2;
ans = 0;
for(int i = 2; i <= n; i++)
{
a[t++] = a[i];
while(t >= 4 && a[t-3] <= a[t-1]) Union(t-2);
}
while(t > 2) Union(t-1);
printf("%lld\n", ans);
return 0;
}