zoukankan      html  css  js  c++  java
  • 动态DP

    (code:)

    struct matrix
    {
        int a[2][2];
        matrix()
        {
            a[0][0]=a[0][1]=a[1][0]=a[1][1]=-inf;
        }
    }val[maxn],mul[maxn];
    matrix operator *(const matrix &x,const matrix &y)
    {
        matrix z;
        for(int k=0;k<=1;++k)
            for(int i=0;i<=1;++i)
                for(int j=0;j<=1;++j)
                    z.a[i][j]=max(z.a[i][j],x.a[i][k]+y.a[k][j]);
        return z;
    }
    void pushup(int x) 
    {
        mul[x]=val[x];
        int ls=ch[x][0],rs=ch[x][1];
        if(ls) mul[x]=mul[ls]*mul[x];
        if(rs) mul[x]=mul[x]*mul[rs];
    }
    bool check(int x)
    {
        return ch[fa[x]][1]==x;
    }
    bool notroot(int x)
    {
        return ch[fa[x]][0]==x||ch[fa[x]][1]==x;
    }
    void rotate(int x)
    {
        int y=fa[x],z=fa[y],k=check(x),w=ch[x][k^1];
        if(notroot(y)) ch[z][check(y)]=x;
        fa[x]=z;
        ch[y][k]=w;
        if(w) fa[w]=y;
        ch[x][k^1]=y;
        fa[y]=x;
        pushup(y);
        pushup(x);
    }
    void all(int x)
    {
        if(notroot(x)) all(fa[x]);
    }
    void splay(int x)
    {
        all(x);
        for(int y;notroot(x);rotate(x))
            if(notroot(y=fa[x]))
                rotate(check(x)^check(y)?x:y);
    }
    void access(int x)
    {
        for(int y=0;x;y=x,x=fa[x])
        {    
            splay(x);
            if(ch[x][1])
            {
                val[x].a[0][0]+=max(mul[ch[x][1]].a[0][0],mul[ch[x][1]].a[1][0]);
                val[x].a[1][0]+=mul[ch[x][1]].a[0][0];
            }
            if(y)
            {
                val[x].a[0][0]-=max(mul[y].a[0][0],mul[y].a[1][0]);
                val[x].a[1][0]-=mul[y].a[0][0];
            }
            val[x].a[0][1]=val[x].a[0][0];
            ch[x][1]=y;
            pushup(x);
        }
    }
    void modify(int x,int v)
    {
        access(x),splay(x);
        val[x].a[1][0]-=a[x]-v;
        pushup(x);
        a[x]=v;
    }
    void dfs(int x,int fath)
    {
        fa[x]=fath;
        f[x][1]=a[x];
        for(int i=head[x];i;i=e[i].nxt)
        {
            int y=e[i].to;
            if(y==fath) continue;
            dfs(y,x);
            f[x][0]+=max(f[y][0],f[y][1]);
            f[x][1]+=f[y][0];
        }
        val[x].a[0][0]=val[x].a[0][1]=f[x][0];
        val[x].a[1][0]=f[x][1],mul[x]=val[x];
    }
    
  • 相关阅读:
    腾讯//全排列
    腾讯//全排列
    腾讯//子集
    腾讯//子集
    腾讯///括号生成
    腾讯///括号生成
    腾讯//二叉树的最近公共祖先
    腾讯//二叉树的最近公共祖先
    腾讯//二叉搜索树的最近公共祖先
    腾讯//二叉搜索树的最近公共祖先
  • 原文地址:https://www.cnblogs.com/lhm-/p/12229778.html
Copyright © 2011-2022 走看看