• 石子合并,GarsiaWachs算法优化


     

    思路:

    可以发现朴素的区间dp已经不足以解决这个问题了。对于石子合并问题,有一个最好的算法,那就是GarsiaWachs算法。时间复杂度为O(n^2)。

    设序列是stone[maxn],从左往右,找到一个最小的且满足stone[k-1] <= stone[k+1]的k,找到后合并stone[k]和stone[k-1],再从当前位置开始向左找一个j满足stone[j] >= stone[k]+stone[k-1],然后把stone[k]+stone[k-1]插到j的后面就行。一直重复,直到只剩下一堆石子就可以了。
    另外在这个过程中,可以假设stone[-1]和stone[n]是正无穷的,可省略边界的判别。把stone[0]设为inf, stone[n+1]设为inf-1,可实现剩余一堆石子时自动结束。


    举个例子:
    186 64 35 32 103
    因为35<103,所以最小的k是3(下标从0开始),我们先把35和32删除,得到他们的和67,并向前寻找一个第一个大于等于67的数,把67插入到他后面,得到:186 67 64 103,现在由5个数变为4个数了,继续:186 131 103,之后得到234 186,k=2(别忘了,设A[-1]和A[n]等于正无穷大),最后得到420。最后的答案呢?就是各次合并的重量之和,即420+234+131+67=852。


    基本思想是通过树的最优性得到一个节点间深度的约束,之后证明操作一次之后的解可以和原来的解一一对应,并保证节点移动之后他所在的深度不会改变。具体实现这个算法需要一点技巧,精髓在于不停快速寻找最小的k,即维护一个“2-递减序列”朴素的实现的时间复杂度是O(n*n),但可以用一个平衡树来优化,使得最终复杂度为O(nlogn)。
    AC_Code

    #include <cstdio>
    #include <cstring>
    #include <string>
    #include <cmath>
    #include <queue>
    #include <stack>
    #include <vector>
    #include <set>
    #include <map>
    #include <algorithm>
    using namespace std;
    typedef long long ll;
    const int maxn=50005;
    const ll mod=1e9+7;
    const int inf=0x3f3f3f3f;
    const double eps = 1e-9;
    int stone[maxn],n,ans,t;
    
    void combine(int k){
        int tmp=stone[k-1]+stone[k];
        ans+=tmp;
        --t;
        for(int i=k;i<t;i++) stone[i]=stone[i+1];
        int j;
        for(j=k-1;stone[j-1]<tmp;--j){
            stone[j]=stone[j-1];
        }
        stone[j]=tmp;
        while( j>=2 && stone[j]>=stone[j-2] ){
            int d=t-j;
            combine(j-1);
            j=t-d;
        }
    }
    
    int main()
    {
        while( ~scanf("%d",&n)&&n){
            stone[0]=inf; stone[n+1]=inf-1;
            for(int i=1;i<=n;i++){
                scanf("%d",&stone[i]);
            }
            ans=0;
            t=3;
            for(int i=3;i<=n+1;i++){
                stone[t++]=stone[i];
                while( stone[t-3]<=stone[t-1]){
                    combine(t-2);
                }
            }
            while( t>3 ) combine(t-1);
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    这个帖子主要总结数据库备份方面的问题
    Visual C#.Net 网络程序开发Socket篇
    数据库设计说明书参考模板
    用Visual C#开发WinForm的应用程序
    在ASP.NET页中读取文本文件
    如何通过 SQL Server 链接服务器和分布式查询使用 Excel
    ER概念模型
    SQL Server 存储过程的分页方案比拼
    读出某一个目录的文件和文件夹
    Linux中的定时任务简单操作实例
  • 原文地址:https://www.cnblogs.com/wsy107316/p/12252407.html
Copyright © 2020-2023  润新知