Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
2
Indexable
Never
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    cin >> n;
    vector<int> v(n);
    for (int i = 0; i < n; i++)
        cin >> v[i];
    vector<int> pref(n);
    for (int i = 1; i < n; i++)
    {
        if (i % 2 == 0)
        {
            pref[i] = pref[i - 1] + v[i] - v[i - 1];
        }
        else
            pref[i] = pref[i - 1];
    }
    cout<<'\n';
    int q;
    cin >> q;
    while (q--)
    {
        int ans = 0;
        int l, r;
        cin >> l >> r;
        int low = 0;
        int high = n - 1;
        int ans_1 = 0;
        int ans_2 = 0;
        while (low <= high)
        {
            int mid = low + (high - low) / 2;
            if (v[mid] >= l)
            {
                ans_1 = mid;
                high = mid - 1;
            }
            else
                low = mid + 1;
        }
        low = 0;
        high = n - 1;
        while (low <= high)
        {
            int mid = low + (high - low) / 2;
            if (v[mid] <= r)
            {
                ans_2 = mid;
                low = mid + 1;
            }
            else
                high = mid - 1;
        }
        if (ans_1 % 2 == 0)
            ans += v[ans_1] - l;
        if (ans_2 % 2 != 0)
            ans += r - v[ans_2];
        ans += pref[ans_2] - pref[ans_1];
        cout << ans << '\n';
    }

    return 0;
}