码迷,mamicode.com
首页 > 其他好文 > 详细

动态DP

时间:2020-01-23 00:06:52      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:动态   oid   return   spl   max   hup   math   cpp   struct   

\(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];
}

动态DP

标签:动态   oid   return   spl   max   hup   math   cpp   struct   

原文地址:https://www.cnblogs.com/lhm-/p/12229778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!