---
id: 2367
lang: en
translation_of: index.md
source_sha256: 1389ba58150afc3f1ed8fa0d63670d083f4928324e7893e8fa4e2095cc837d45
title: "P4425: [HNOI/AHOI2018] Turntable — Solution"
description: "The first problem I've done that uses a segment tree to maintain a monotonic stack, so let me write a blog post about it."
tags: ["OI","Segment Tree","Monotonic Stack"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "去搞搞 (casual “go mess with it”) rendered as “have a go at it”, without a chip, as plain casual wording."
---

## Main Idea

This is the first problem I've done that uses a segment tree to maintain a monotonic stack, so let me write a blog post about it.

First, what this problem asks for is just $ans =  \min_{i \in [n, 2n)} \max_{j \in [i - n + 1, i]} a_j + i - j$; rewriting it a bit gives $ans =  (\min_{i \in [1, n)} \max_{j \in [i, i + n - 1]} a_j + i - j) + n - 1$.

We can consider computing $B_i = a_i - i$ and then taking the $\min$. However, the complexity of this is still high. When we consider the static problem, we find that this problem can actually be done in $\Theta(n)$, because all it really takes is a reversed (right-to-left) monotonic stack.

Moving on to the dynamic problem, we can try to have a go at it with a segment tree: when merging, first keep the contents of the right subtree, then try binary searching in the left subtree to find the tail of the queue, and that's it.

<!--more-->

## Code

```cpp
// P4425.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 2e5 + 200, INF = 0x3f3f3f3f;

int n, m, typ, Ti[MAX_N], nodes[MAX_N << 2], tag[MAX_N << 2];

#define lson (p << 1)
#define rson ((p << 1) | 1)
#define mid ((l + r) >> 1)

int query(int qx, int l, int r, int p)
{
    if (l == r)
        return nodes[p] > qx ? qx + l : INF;
    return nodes[rson] > qx ? min(tag[p], query(qx, mid + 1, r, rson)) : query(qx, l, mid, lson);
}

void pushup(int p, int l, int r)
{
    nodes[p] = max(nodes[lson], nodes[rson]);
    tag[p] = query(nodes[rson], l, mid, lson);
}

void build(int l, int r, int p)
{
    if (l == r)
        return (void)(nodes[p] = Ti[l] - l, tag[p] = INF);
    build(l, mid, lson), build(mid + 1, r, rson);
    pushup(p, l, r);
}

void update(int qx, int l, int r, int p, int val)
{
    if (l == r)
        return (void)(nodes[p] = val - l);
    if (qx <= mid)
        update(qx, l, mid, lson, val);
    else
        update(qx, mid + 1, r, rson, val);
    pushup(p, l, r);
}

#undef mid
#undef rson
#undef lson

int main()
{
    scanf("%d%d%d", &n, &m, &typ);
    for (int i = 1; i <= n; i++)
        scanf("%d", &Ti[i]);
    int lastans;
    build(1, n, 1), printf("%d\n", lastans = query(nodes[1] - n, 1, n, 1) + n);
    while (m--)
    {
        int x, y;
        scanf("%d%d", &x, &y), x ^= typ * lastans, y ^= typ * lastans;
        update(x, 1, n, 1, y);
        printf("%d\n", lastans = query(nodes[1] - n, 1, n, 1) + n);
    }
    return 0;
}
```
