Xaleid◆scopiX 题解

· · 题解

设 f_i 表示前 i 个数里最后一个选的是 i 的最大总和,显然有 dp 式 f_i = a_i + \max_{j<i-r_i,j+r_j<i}{f_j}。

限制有两个,分别是 j<i-r_i 和 j+r_j<i。对于第一条限制,合法的 j 是一个前缀,现在需要求一个前缀内满足第二条限制的最大值。

对于第二条限制,可以从主动转移的角度来看,对于每个 j,合法的 i 是一个后缀。

考虑树状数组优化 dp,每次求 dp 值直接 a[i] + ask(i - r[i] - 1),然后在能贡献的起点的位置 (即 i+r_i+1)处在树状数组中加入 f_i。

时间复杂度 O(n\log n),可以通过此题。

#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;
}