题解P11325
树形 DP。
对于排列中的某一个位置
容易发现,如果
然后,我们把
例如,对于样例
这棵树存在这样的性质:如果某个点对答案造成了贡献,则以该点为根的子树里的所有的点都对答案造成了贡献。
但是,叶节点是特殊的。首先,由题可知,单调队列一旦被从队尾删空,就一定会加入一个新的点,使得队列非空。另外,类似样例
根据以上两点,叶节点对答案造成的贡献有这样的规则:存在一个整数
此外,最右侧的链由于到结束也还在单调队列中,也没法对答案造成贡献。
例如对于上图,可能的对答案造成贡献的组合只有以下几种:
1
1 2
1 2 3
1 2 3 6 5
1 2 3 6 5 7 4
1 2 3 6 5 7 4 9
1 2 3 6 5 7
1 2 3 6 5 7 9
1 2 3 6
1 2 3 6 7
1 2 3 6 7 9
于是,我们有了一个树形 DP。
设
如果不选
如果选
时间复杂度
代码很短:
#include<bits/stdc++.h>
#define LL long long
#define Maxn 500005
using namespace std;
int n,a[Maxn],c[Maxn];
stack<int> q;
vector<int> e[Maxn];
LL f[Maxn],g[Maxn],all[Maxn];
void dfs(int x){
all[x] = c[x];
if(e[x].empty()){
f[x] = c[x];
g[x] = max(0, c[x]);
return;
}
for(int y : e[x]){
dfs(y);
all[x] += all[y];
g[x] = max(g[x], f[x] + g[y]);
f[x] += f[y];
}
f[x] = max(f[x], all[x]);
g[x] = max(g[x], all[x]);
}
int main(){
scanf("%d",&n);
for(int i=1; i<=n; i++) scanf("%d",c+i);
for(int i=1; i<=n; i++) scanf("%d",a+i);
q.emplace(0);
for(int i=1; i<=n; i++){
while(q.size() > 1 && a[q.top()] <= a[i]){
q.pop();
}
e[q.top()].emplace_back(i);
q.emplace(i);
}
while(!q.empty()){
c[q.top()] = 0; q.pop();
}
dfs(0);
printf("%lld\n", g[0]);
return 0;
}