HDU 5735 Born Slippy

看官方题解很详细了:

总结一下:递推式不难想到,但是每次求dp[x]需要枚举祖先,复杂度太高,需要优化。

题解的方法,可以使得复杂度降低到1<<24.

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-8;
void File()
{
    freopen("D:\\in.txt","r",stdin);
    freopen("D:\\out.txt","w",stdout);
}
inline int read()
{
    char c = getchar();  while(!isdigit(c)) c = getchar();
    int x = 0;
    while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); }
    return x;
}

const LL mod=1e9+7;
const int maxn=(1<<16)+10;
int T,n;
char op[5];
LL w[maxn],dp[maxn],g[300][300],t[maxn][258];
int h[maxn],tot;
struct Edge {int v,nx;}e[maxn];
int f[300];

LL get(LL a,LL b)
{
    if(op[0]=='A') return a&b;
    else if(op[0]=='O') return a|b;
    else return a^b;
}

void dfs(int x)
{
    LL a=w[x]>>8, b=w[x]-(a<<8);

    for(int i=0;i<256;i++)
        if(f[i]) dp[x]=max(dp[x],g[i][b]+(get((LL)i,a)<<8));

    for(int i=0;i<256;i++) t[x][i]=g[a][i]; f[a]++;
    for(int i=0;i<256;i++) g[a][i]=max(g[a][i],dp[x]+get(b,(LL)i));
    for(int i=h[x];i!=-1;i=e[i].nx) dfs(e[i].v);
    for(int i=0;i<256;i++) g[a][i]=t[x][i]; f[a]--;
}

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n); scanf("%s",op);
        for(int i=1;i<=n;i++) scanf("%lld",&w[i]);
        tot=0; memset(h,-1,sizeof h);
        for(int i=2;i<=n;i++)
        {
            int fa;scanf("%d",&fa);
            e[tot].v=i,e[tot].nx=h[fa],h[fa]=tot++;
        }
        memset(f,0,sizeof f);
        memset(dp,0,sizeof dp);
        memset(g,0,sizeof g); dfs(1);
        LL ans=0;
        for(int i=1;i<=n;i++)
            ans=(ans+(i*(w[i]+dp[i])%mod)%mod)%mod;
        printf("%lld\n",ans);
    }
    return 0;
}

 

posted @ 2016-07-24 11:50  Fighting_Heart  阅读(170)  评论(0编辑  收藏  举报