Submission #1370150

#TimeUsernameProblemLanguageResultExecution timeMemory
1370150chikien2009Bitaro's travel (JOI23_travel)C++20
100 / 100
306 ms29580 KiB
#include <bits/stdc++.h>

using namespace std;

void setup()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
}

template <class comp>
struct RMQ
{
    int n;
    int sp[20][200000];
    comp compare;
    inline int *operator[](int ind)
    {
        return sp[ind];
    }
    inline void Init(int new_n)
    {
        n = new_n;
    }
    inline void Build()
    {
        for (int i = 1; i <= __lg(n); ++i)
        {
            for (int j = 0; j + (1 << i) <= n; ++j)
            {
                if (compare(sp[i - 1][j], sp[i - 1][j + (1 << (i - 1))]))
                {
                    sp[i][j] = sp[i - 1][j];
                }
                else
                {
                    sp[i][j] = sp[i - 1][j + (1 << (i - 1))];
                }
            }
        }
    }
};

int n, q, b, c, l, r, dir;
int a[200000];
long long res;
RMQ<greater<int>> pre;
RMQ<less<int>> suf;

inline int GetPre(int x, int v)
{
    for (int i = __lg(n); i >= 0 && x >= 0; --i)
    {
        if (0 <= x - (1 << i) + 1 && pre[i][x - (1 << i) + 1] <= v)
        {
            x -= (1 << i);
        }
    }
    return x;
}

inline int GetSuf(int x, int v)
{
    for (int i = __lg(n); i >= 0 && x < n; --i)
    {
        if (x + (1 << i) - 1 < n && v < suf[i][x])
        {
            x += (1 << i);
        }
    }
    return x;
}

int main()
{
    setup();

    cin >> n;
    pre.Init(n);
    suf.Init(n);
    for (int i = 0; i < n; ++i)
    {
        cin >> a[i];
        if (0 < i)
        {
            pre[0][i - 1] = 2 * a[i] - a[i - 1];
            suf[0][i] = 2 * a[i - 1] - a[i];
        }
    }
    pre.Build();
    suf.Build();
    cin >> q;
    while (q--)
    {
        cin >> b;
        res = 0;
        r = lower_bound(a, a + n, b) - a;
        l = r - 1;
        dir = (a[r] - b < b - a[l]);
        while (0 <= l && r < n)
        {
            if (dir == 0)
            {
                c = GetPre(l - 1, a[r]) + 1;
                l = c - 1;
            }
            else
            {
                c = GetSuf(r + 1, a[l]) - 1;
                r = c + 1;
            }
            res += abs(b - a[c]);
            b = a[c];
            dir ^= 1;
        }
        cout << res + (r == n ? b - a[0] : a[n - 1] - b) << "\n";
    }
    return 0;
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...