[其它-GarsiaWachs算法]51nod 1023 石子归并v3

来源:互联网 发布:杭州汉聚网络怎么样 编辑:程序博客网 时间:2024/04/28 12:20

1023 石子归并 V3

基准时间限制:2 秒 空间限制:131072 KB 分值: 640 难度:8级算法题

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

这道题用GarsiaWachs算法,时间复杂度达到O(nlogn)操作过程如下:

对于剩下来的k堆石子,如果存在一个最小的i,满足data[i-2]<=data[i],那么就可以优先合并data[i-2]和data[i-1]这两堆。

证明略。。。。。。。

 

拿代码感受一下。

#include <stdio.h>#include <algorithm>#include <iostream>#include <string.h>#define MAXN 50005#define LL long longusing namespace std;int n, num;LL ans;int data[MAXN];void dfs(int now){    int j;    int temp = data[now - 1] + data[now];//代价    ans += (LL)temp;    for(int i = now; i < num - 1; i++) data[i] = data[i + 1];    num--;    for(j = now - 1; j > 0 && data[j - 1] < temp; j--) data[j] = data[j - 1];    data[j] = temp;    while(j >= 2 && data[j - 2] <= data[j])    {        int d = num - j;        dfs(j - 1);        j = num - d;    }}int main(){    scanf("%d", &n);    for(int i = 0; i < n; i++) scanf("%d", &data[i]);    num = 1;    ans = 0;    for(int i = 1; i < n; i++)    {        //printf("%d %d\n",num,i);        data[num++] = data[i];        while(num>=3 && data[num-3]<=data[num-1]) dfs(num - 2);    }    while(num > 1) dfs(num - 1);    printf("%lld\n", ans);    return 0;}
0 0
原创粉丝点击