设 表示前 个数里最后一个选的是 的最大总和,显然有 dp 式 。
限制有两个,分别是 和 。对于第一条限制,合法的 是一个前缀,现在需要求一个前缀内满足第二条限制的最大值。
对于第二条限制,可以从主动转移的角度来看,对于每个 ,合法的 是一个后缀。
考虑树状数组优化 dp,每次求 dp 值直接 a[i] + ask(i - r[i] - 1),然后在能贡献的起点的位置 (即 )处在树状数组中加入 。
时间复杂度 ,可以通过此题。
#include <bits/stdc++.h>
#define lowbit(o) o & -o
#define pb push_back
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int N = 1000005;
const int mod = 92084931;
const int inf = 0x3f3f3f3f;
const LL INF = 2e18;
int r[N], a[N], n;
LL tr[N], f[N];
vector<int> p[N];
inline void add(int x,LL y)
{
for (;x<=n;x+=lowbit(x))
tr[x] = max(tr[x], y);
}
inline LL ask(int x)
{
if (x <= 0)
return 0;
LL res = 0;
for (;x;x-=lowbit(x))
res = max(res, tr[x]);
return res;
}
void work()
{
cin >> n;
for (int i=1;i<=n;i++)
cin >> a[i];
for (int i=1;i<=n;i++)
cin >> r[i];
LL ans = 0;
for (int i=1;i<=n;i++)
{
for (int j : p[i])
add(j, f[j]);
f[i] = ask(i - r[i] - 1) + a[i];
ans = max(ans, f[i]);
if (i + r[i] + 1 <= n)
p[i + r[i] + 1].pb(i);
}
cout << ans;
}
signed main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int _T = 1;
//cin >> _T;
while (_T--)
work();
return 0;
}