CF1927 D. Find the Different Ones!

· · 题解

给定一个长度为 n 的数组 a。

你需要处理 q 次询问。每次询问给定两个整数 l, r,你需要找到任意两个整数 i, j 使得:

若无解,输出 i = j = -1。

多测。t \le 10^4,\sum n \le 2 \times 10^5,\sum q \le 2 \times 10^5,1 \le l < r \le n,1 \le a_i \le 10^6。

如果最终答案是 i, j,不妨设 a_i \le a_j,那么根据 a_i \ne a_j,一定可以推出 a_j - a_i > 0。

我们不妨使这个差值最大。那么不难看出只有区间内最大值和最小值的差值最大。

那么当区间内最大值和最小值相等时无解。

所以用 ST 表维护区间最小值和最大值的位置即可。实现上略有技巧。

int n, a[N];

struct RMQ {
    bool op;
    RMQ(bool _op) : op(_op) {}
    int st[N][20];

    int minn(int x, int y) {
        return op ? (a[x] < a[y] ? x : y) : (a[x] > a[y] ? x : y);
    }

    void init() {
        fup (i, 1, n) st[i][0] = i;

        fup (j, 1, 19)
            for (int i = 1; i + (1 << j - 1) <= n; ++ i ) {
                st[i][j] = minn(st[i][j - 1], st[i + (1 << j - 1)][j - 1]);
            }
    }

    int query(int l, int r) {
        int k = log2(r - l + 1);
        return minn(st[l][k], st[r - (1 << k) + 1][k]);
    }

    void clear() {
        fup (i, 1, n)
            fup (j, 0, 19)
                st[i][j] = 0;
    }
}A(false), B(true);

void solve() {
    n = read();
    fup (i, 1, n) a[i] = read();
    A.init(), B.init();
    for (int q = read(); q -- ; ) {
        int l = read(), r = read();
        int x = A.query(l, r), y = B.query(l, r);
        if (a[x] == a[y]) puts("-1 -1");
        else wel(x, y);
    }

    A.clear(), B.clear();

    puts("");
    return;
}