基准时间限制: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
题解:一般作法就是用四边形优化成n^2,但本题会T。
有一个算法叫GarsiaWachs,具体请看链接点击打开链接
然后直接n^2暴力过即可,因为常数非常非常小~链接中有说
AC代码
#include <stdio.h> #include <iostream> #include <string> #include <queue> #include <map> #include <vector> #include <algorithm> #include <string.h> #include <cmath> typedef long long ll; using namespace std; const ll maxn = 5e4 + 10, inf = 0x7fffffffffffffff; ll a[maxn], n, ans; ll dfs(ll x){ ll temp = a[x] + a[x + 1]; ans += temp; ll i = x; for(; temp > a[i]; i--) a[i] = a[i - 1]; a[i + 1] = temp; for(ll j = x + 1; j <= n; j++) a[j] = a[j + 1]; n--; return i + 1; } int main(){ ans = 0; scanf("%lld", &n); for(ll i = 1; i <= n; i++) scanf("%lld", &a[i]); a[0] = a[n + 1] = inf; for(ll i = 1; i <= n - 1;){ if(a[i] <= a[i + 2]) i = max(dfs(i) - 2, (ll)1); else i++; } while(n > 1) dfs(n - 1); printf("%lld\n", ans); return 0; }真的很神奇啊,这算法,明天一定要去看看证明过程!!!论文大佬是真的强啊!