제출 #1359945

#제출 시각아이디문제언어결과실행 시간메모리
1359945PetiFish 3 (JOI24_fish3)C++20
100 / 100
305 ms109052 KiB
#include <bits/stdc++.h>
using namespace std;

const int logn = 20;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int n;
    long long d;
    cin>>n>>d;
    
    vector<long long> v(n);
    for(auto &x : v) cin>>x;

    vector<long long> diff(n);
    for(int i = 0; i < n - 1; i++) {
        if(v[i] <= v[i+1]) diff[i] = (v[i] - v[i + 1]) / d;
        else diff[i] = (v[i] - v[i + 1] + d - 1) / d;
    }
    diff[n-1] = 0;

    vector<long long> suf = diff;
    for(int i = n-2; i >= 0; i--) {
        suf[i] += suf[i + 1];
    }
    vector<long long> suf2 = suf;
    for(int i = n-2; i >= 0; i--) {
        suf2[i] += suf2[i + 1];
    }

    vector<array<pair<int, long long>, logn>> st(n);
    for(int i = 0; i < n; i++) {
        int idx = i - 1;
        while(idx >= 0 && suf[idx] >= suf[i]) idx = st[idx][0].first;
        st[i][0].first = idx;
    }

    // cout << "suf: ";
    // for(auto x : suf) cout << x << ' ';
    // cout << '\n';
    // cout << "suf2: ";
    // for(auto x : suf2) cout << x << ' ';
    // cout << '\n';

    for(int i = 0; i < n; i++) {
        st[i][0].second = suf2[st[i][0].first + 1] - suf2[i] - (i - (st[i][0].first + 1)) * suf[i];
        // cout << i << " | " << st[i][0].first << " | " << st[i][0].second << '\n';
    }

    for(int i = 0; i < n; i++) {
        for(int j = 1; j < logn; j++) {
            if(st[i][j-1].first != -1) {
                st[i][j].first = st[st[i][j-1].first][j-1].first;
                st[i][j].second = st[st[i][j-1].first][j-1].second + st[i][j-1].second;
            } else {
                st[i][j].first = -1;
                st[i][j].second = 0;
            }
        }
    }

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

        int x = r;
        long long ans = 0;
        for(int j = logn - 1; j >= 0; j--) {
            if(st[x][j].first >= l) {
                // cout << "jump: " << j << " | " << st[x][j].first << '\n';
                ans += st[x][j].second;
                x = st[x][j].first;
            }
        }
        ans += (suf2[l] - suf2[x]) - (x - l) * suf[x];
        if(v[l] - (suf[l] - suf[x]) * d < 0) {
            cout << -1 << '\n';
        } else {
            cout << ans << '\n';
        }
    }


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