本文搬运自本人初中博客园博客,若图片加载不出来,可到原文查看:https://www.cnblogs.com/zhangtingxi/p/15600574.html

题目链接

典型的树形dp。

dp(x,i)dp(x, i) 表示 xx 的子树内逗留 ii 秒的作品最大值。

dp(x,i)=maxyxmaxi=0smaxj=2×zidp(y,j2×z)dp(x,ji)dp(x, i)=\max_{y\in x}\max_{i=0}^s\max_{j=2\times z}^i dp(y,j-2\times z)-dp(x,j-i)

实际实现时有一些先后顺序和细节,调整一下即可。

建边方面可以用一个栈来实现。

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Problem: P1270 “访问”美术馆
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1270
// Memory Limit: 125 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
#define M 600
//#define mo
#define N 510
struct node
{
int x, y, z, n;
}d[N*4];
int n, m, i, j, k;
int a[N], dp[N][M], h[N], f[M];
int zhan[N], top, x, y, s;

void cun(int x, int y, int z)
{
// printf("%lld %lld %lld\n", x, y, z);
++m;
d[m].x=x; d[m].y=y; d[m].z=z;
d[m].n=h[x]; h[x]=m;
}

void dfs(int x)
{
if(a[x])
{
for(int i=0; i<=a[x]&&i*5<=s; ++i)
dp[x][i*5]=i;
for(int i=1; i<=s; ++i)
if(!dp[x][i]) dp[x][i]=dp[x][i-1];
// printf("dp[%lld]=%lld\n", x, dp[x][s]);
return ;
}
for(int g=h[x]; g; g=d[g].n)
{
int y=d[g].y;
dfs(y);
// memset(f, 0, sizeof(f));
for(int j=0; j<=s; ++j) f[j]=dp[x][j];
for(int j=s; j>=0; --j)
for(int i=j; i>=d[g].z*2; --i)
dp[x][j]=max(dp[x][j], dp[y][i-d[g].z*2]+f[j-i]);
}
// printf("dp[%lld]=%lld\n", x, dp[x][s]);
}

signed main()
{
// freopen("tiaoshi.in", "r", stdin);
// freopen("tiaoshi.out", "w", stdout);
s=read()-1;
zhan[top=1]=k=1;
while(scanf("%lld%lld", &x, &y)!=EOF)
{
if(y==0) cun(zhan[top--], ++k, x), zhan[++top]=k, zhan[++top]=k;
else cun(zhan[top--], ++k, x), a[k]=y;
}
dfs(1);
printf("%lld", dp[1][s]);
return 0;
}