洛谷 P4436 [HNOI/AHOI2018]游戏(DP)

传送门


今天信心赛第一题,其实真的不是很难,只是我太弱不会。。
其实就是DP啦。
公路起点记为左儿子,铁路起点记为右儿子,从根开始深搜做DP,f[i][j][k]表示走到第i个节点,重修了j条公路与k条铁路的最小贡献。

转移方程:
f [ i ] [ j ] [ k ] = m a x ( d f s ( s o n [ 0 ] , j + 1 , k ) + d f s ( s o n [ 1 ] , j , k ) , d f s ( s o n [ 0 ] , j , k ) + d f s ( s o n [ 1 ] , j , k + 1 ) )

复杂度大概是 O ( 20000 40 40 )

Code:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#define ll long long
using namespace std;

struct node{ll son[2];}tr[20010];
ll a[20010],b[20010],c[20010],f[20010][42][42];
ll n;

void read(ll &sum)
{
    char ch=getchar();
    sum=0;int f=0;
    while((ch<'0'||ch>'9')&&(ch!='-')) ch=getchar();
    f=((ch=='-')&&(ch=getchar()));
    while(ch>='0'&&ch<='9') sum=sum*10+(ch-48),ch=getchar();
    (f)&&(sum=-sum);
}

ll min(ll x,ll y)
{
    return x<y?x:y;
}

ll dfs(int i,int j,int k)
{
    if(i>=n) return c[i-n+1]*(a[i-n+1]+j)*(b[i-n+1]+k);
    if(f[i][j][k]<f[0][0][0]) return f[i][j][k]; 
    return f[i][j][k]=min(dfs(tr[i].son[0],j+1,k)+dfs(tr[i].son[1],j,k),dfs(tr[i].son[0],j,k)+dfs(tr[i].son[1],j,k+1));
}

int main()
{
    read(n);
    for(int i=1;i<n;i++)
    {
        ll x,y;
        read(x);read(y);
        if(x<0) x=-x-1+n;
        if(y<0) y=-y-1+n;
        tr[i].son[0]=x;
        tr[i].son[1]=y;
    }
    for(int i=1;i<=n;i++)
    {
        read(a[i]);read(b[i]);read(c[i]);
    }
    memset(f,63,sizeof(f));
    printf("%lld",dfs(1,0,0));
}

猜你喜欢

转载自blog.csdn.net/Dawn_LLLLLLL/article/details/80054966