Solution of P6240 好吃的题目

· · 题解

你可以浏览这个题解的中文版本。

The images are hosted on Github, use an accelerator if it fails to load.

Disjoint Sparse Table's Template Problem.

Consider how to compute the answer in the interval [l,\text{mid}] with capacity i when it is known that f_i denotes the answer in the interval [l,\text{mid}] with capacity i, and g_i denotes the answer in the interval [\text{mid}+1,r] with capacity i. It is not difficult to have a direct calculation \text{merge}(f,g)=\max\{f_i+g_{v-i}\}. Complexity \mathcal{O}(n).

Let the query interval be [a,b]. If the interval [l,r] satisfies l\le a\le\text{mid}\le b\le r, then the answer is \text{merge}(f,g). The problem then transforms into how to find an interval that satisfies the condition in this way.

For the interval [l,r] that satisfies l\le a\le b\le r, we discuss the following three cases:

  1. when a\le\text{mid}<b, it is straightforward to compute the answer;
  2. when a\le b\le\text{mid}, recursing down the interval [l,\text{mid}];
  3. when \text{mid}<a\le b, recurse down the interval [\text{mid}+1,r].

Since this is offline, you can save space by considering all queries recursive to the same interval together, and just calculate f,g when you need to use it. Complexity \mathcal{O}(v\cdot n\log n).

#include <bits/stdc++.h>
using namespace std;
// #define int long long
#define endl '\n'
const int N = 4e4 + 5, M = 2e2 + 5, Q = 2e5 + 5, V = 2e2;
int n, q, v[N], w[N], ans[Q], f[N][M], g[N][M]; 
struct Node {
    int l, r, t, i;
};
void solve(vector<Node> &p, int l, int r) {
    int m = (l + r) / 2;
    vector<Node> nl, nm, nr;
    for(auto [xl, xr, t, i] : p) 
        if(xl <= m && xr <= m) nl.push_back({xl, xr, t, i}); 
        else if(xl <= m && xr > m) nm.push_back({xl, xr, t, i});
        else if(xl > m && xr > m) nr.push_back({xl, xr, t, i});
        else assert(0);
    if(!nl.empty()) solve(nl, l, m);
    if(!nr.empty()) solve(nr, m + 1, r);
    if(!nm.empty()) {
        for(int j = 0; j <= V; j++) f[m + 1][j] = 0;
        for(int i = m; i >= l; i--) for(int j = 0; j <= V; j++)
            if(j >= v[i]) f[i][j] = max(f[i + 1][j], f[i + 1][j - v[i]] + w[i]);
            else f[i][j] = f[i + 1][j];
        for(int j = 0; j <= V; j++) g[m][j] = 0;
        for(int i = m + 1; i <= r; i++) for(int j = 0; j <= V; j++)
            if(j >= v[i]) g[i][j] = max(g[i - 1][j], g[i - 1][j - v[i]] + w[i]);
            else g[i][j] = g[i - 1][j];
        for(auto [xl, xr, t, i] : nm)
            for(int a = 0, b = t; a <= t; a++, b--)
                ans[i] = max(ans[i], f[xl][a] + g[xr][b]);
    }
}
signed main() {
    cin>>n>>q;
    for(int i = 1; i <= n; i++) cin>>v[i];
    for(int i = 1; i <= n; i++) cin>>w[i];
    vector<Node> p;
    for(int i = 1; i <= q; i++) {
        int l, r, t; cin>>l>>r>>t;
        if(l == r) ans[i] = (t >= v[l] ? w[l] : 0);
        else p.push_back({l, r, t, i});
    }
    solve(p, 1, n);
    for(int i = 1; i <= q; i++) cout<<ans[i]<<endl;
}