제출 #1342542

#제출 시각아이디문제언어결과실행 시간메모리
1342542vjudge1Sum Zero (RMI20_sumzero)C++20
61 / 100
409 ms45284 KiB
#include <bits/stdc++.h>
using namespace std;

static const int MAXN = 400000 + 5;
static const int LOG = 20;

int n, q;
long long a[MAXN], pre[MAXN];
int up[LOG][MAXN];
int pw[LOG];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        pre[i] = pre[i - 1] + a[i];
    }

    // Coordinate compression for prefix sums
    vector<long long> vals(pre, pre + n + 1);
    sort(vals.begin(), vals.end());
    vals.erase(unique(vals.begin(), vals.end()), vals.end());

    vector<int> id(n + 1);
    for (int i = 0; i <= n; i++) {
        id[i] = lower_bound(vals.begin(), vals.end(), pre[i]) - vals.begin();
    }

    // up[0][i] = earliest position j such that there exists a zero-sum subarray
    // starting after i and ending at j, greedily earliest possible
    for (int i = 0; i <= n + 1; i++) up[0][i] = n + 1;

    vector<int> last(vals.size(), -1);

    for (int i = 0; i <= n; i++) {
        if (last[id[i]] != -1) {
            up[0][last[id[i]]] = i;
        }
        last[id[i]] = i;
    }

    // suffix minimum
    for (int i = n - 1; i >= 0; i--) {
        up[0][i] = min(up[0][i], up[0][i + 1]);
    }
    up[0][n] = n + 1;
    up[0][n + 1] = n + 1;

    pw[0] = 1;
    for (int k = 1; k < LOG; k++) pw[k] = pw[k - 1] << 1;

    // binary lifting
    for (int k = 1; k < LOG; k++) {
        for (int i = 0; i <= n + 1; i++) {
            up[k][i] = up[k - 1][ up[k - 1][i] ];
        }
    }

    cin >> q;
    while (q--) {
        int l, r;
        cin >> l >> r;

        int cur = l - 1;
        int ans = 0;

        for (int k = LOG - 1; k >= 0; k--) {
            if (up[k][cur] <= r) {
                ans += pw[k];
                cur = up[k][cur];
            }
        }

        cout << ans << '\n';
    }

    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...