题解:P13522 [KOI 2025 #2] 机器人

· · 题解

把数轴用跳跃台分割成若按个区间。由于每次跳到跳跃台上跳跃力量都会翻倍,所以每个跳跃台经过的次数最多为 \log 10^{17} 级别的。计算机器人经过某个跳跃台的情况,可以 O(1) 向左移动若干部,再每次向右移动。单次时间复杂度为 O(\log 10^{17})。

对于所有的 1 \leq i < n,我们可以计算从 i 跳台跳到下一个跳到的跳台 j 所需的时间。注意 j 有可能不等于 i + 1。这样我们可以将 i 和 j 连一条边,边权是耗时,就会得到一颗树。对于每个节点u,倍增算出 u 的 2^i 级祖先 f_{u, i},和到其距离 d_{u, i}。

接下来,对于给定的 s, t,可以二分查找出在 s 左边包括自己的最近的跳跃台的编号 x。

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 3e5 + 7;
int n, fa[N], f[N][70], dis[N], d[N][70], q;
pair<int, int> p[N], p1[N];
map<int, int> mp;
signed main() {
    ios :: sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i ++) {
        cin >> p[i].first >> p[i].second, p1[i] = p[i];
        mp[p[i].first] = i;
    }
    for(int i = 1; i < n; i ++) {
        int s = p[i].first, t = 0;
        while(1) {
            t ++; s += p[i].second; p[i].second <<= 1;
            int x = upper_bound(p + 1, p + 1 + n, make_pair(s, (int)1e18)) - p - 1;
            if(x != i) {
                t += s - p[x].first;
                fa[i] = x, dis[i] = t;
                break;
            }
            t += s - p[i].first, s = p[i].first;
        }
    }
    for(int i = 1; i < n; i ++) p[i] = p1[i];
    for(int i = 0; i <= 65; i ++) f[n][i] = n;
    for(int i = n - 1; i >= 1; i --) {
        f[i][0] = fa[i], d[i][0] = dis[i];
        for(int j = 1; j <= 65; j ++) {
            f[i][j] = f[f[i][j - 1]][j - 1];
            d[i][j] = d[i][j - 1] + d[f[i][j - 1]][j - 1];
        }
    }
    cin >> q;
    while(q --) {
        int s, t, x; cin >> s >> t;
        if(s < p[1].first) {
            cout << s - t << '\n';
            continue;
        } 
        x = upper_bound(p + 1, p + 1 + n, make_pair(s, (int)1e18)) - p - 1;
        if(s - p[x].first >= t) {
            cout << s - t << '\n';
            continue;
        }
        t -= s - p[x].first, s = p[x].first;
        for(int i = 65; i >= 0; i --) 
            if(t >= d[x][i])
                t -= d[x][i], x = f[x][i];
        s = p[x].first;
        if(!t) {
            cout << s << '\n';
            continue;
        }
        while(1) {
            t --; s += p[x].second, p[x].second <<= 1ll;
            if(s - p[x].first >= t) {
                cout << s - t << '\n';
                break;
            }
            t -= s - p[x].first, s = p[x].first;
        }
        p[x] = p1[x];
    }
    return 0;
}