题解:P14387 [JOISC 2017] 火车旅行 / Railway Trip

· · 题解

设 l_{i,j} 表示从 i 点出发,停靠 2^j 站后能抵达的最左位置,r_{i,j} 表示从 i 点出发,停靠 2^j 站后能抵达的最右位置。

考虑如何更新这两个状态。

因为可以走回头路,所以要从两个端点来更新。

递推式如下:

\begin{aligned} l_{i,j}&=\min(l_{l_{i, j-1}, j-1}, l_{r_{i, j-1}, j-1})\\ r_{i,j}&=\max(r_{l_{i, j-1}, j-1}, r_{r_{i, j-1}, j-1}) \end{aligned}

每次查询时先从较左点向两侧扩展区间,如果该区间没有包含较右点,那么就扩展区间并统计答案。

然后再从较右点向两侧扩展区间,如果两区间没有交,那么扩展区间并统计答案。

最后得到的两区间再扩展一步就一定会有交。

:::success[code]

#include <bits/stdc++.h>
#define int long long
using namespace std;
#define _ 100005
int rd(){int x = 0, f = 1;char c = getchar();for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;for(; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);return x * f;}


int n, k, q;
int a[_], l[_][20], r[_][20], x, y;

void init()
{
    stack <int> s;
    n = rd(), k = rd(), q = rd();
    for(int i = 1; i <= n; i++) a[i] = rd();
    for(int i = 1; i <= n; i++)
    {
        while(s.size() && a[s.top()] < a[i]) s.pop();
        l[i][0] = s.size() ? s.top() : i;
        s.push(i);
    }
    while(s.size()) s.pop();
    for(int i = n; i >= 1; i--)
    {
        while(s.size() && a[s.top()] < a[i]) s.pop();
        r[i][0] = s.size() ? s.top() : i;
        s.push(i);
    }
    for(int j = 1; j < 20; j++)
        for(int i = 1; i <= n; i++)
            l[i][j] = min(l[l[i][j-1]][j-1], l[r[i][j-1]][j-1]),
            r[i][j] = max(r[l[i][j-1]][j-1], r[r[i][j-1]][j-1]);
    return;
}

int solve() 
{
    int ans = 0, ll, rr, L, R;
    x = rd(), y = rd();
    if(x > y) swap(x, y);
    ll = x, rr = x;
    for(int i = 19; i >= 0; i--)
    {
        L = min(l[ll][i], l[rr][i]), R = max(r[ll][i], r[rr][i]);
        if(R < y) 
            ll = L, rr = R, ans += (1 << i);
    }
    x = rr, ll = rr = y;
    for(int i = 19; i >= 0; i--)
    {
        L = min(l[ll][i], l[rr][i]), R = max(r[ll][i], r[rr][i]);
        if(L > x) 
            ll = L, rr = R, ans += (1 << i);
    }
    return ans;
}

signed main()
{
    init();
    while(q--)
        cout << solve() << "\n";
    return 0;
}   

:::