主席树+二分
每次对给定区间从1~区间长度len二分mid,查询区间内第mid大的数是不是大于等于mid。。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 200005;
int n, q, tot, tree[20*N], lc[20*N], rc[20*N], a[N], b[N], root[N];
int buildTree(int l, int r){
int cur = ++tot;
if(l == r) return tot;
int mid = (l + r) >> 1;
lc[cur] = buildTree(l, mid);
rc[cur] = buildTree(mid + 1, r);
return cur;
}
int modify(int rt, int l, int r, int p){
int cur = ++tot;
tree[cur] = tree[rt] + 1, lc[cur] = lc[rt], rc[cur] = rc[rt];
if(l == r) return cur;
int mid = (l + r) >> 1;
if(p <= mid) lc[cur] = modify(lc[cur], l, mid, p);
else rc[cur] = modify(rc[cur], mid + 1, r, p);
return cur;
}
int query(int a, int b, int l, int r, int k){
int p = tree[lc[a]] - tree[lc[b]];
if(l == r) return l;
int mid = (l + r) >> 1;
if(k <= p) return query(lc[a], lc[b], l, mid, k);
return query(rc[a], rc[b], mid + 1, r, k - p);
}
int main(){
while(~scanf("%d%d", &n, &q)){
full(a, 0), full(b, 0), full(tree, 0), full(lc, 0), full(rc, 0), full(root, 0);
for(int i = 1; i <= n; i++) b[i] = a[i] = read();
sort(b + 1, b + n + 1);
int k = unique(b + 1, b + n + 1) - b - 1;
root[0] = buildTree(1, k);
for(int i = 1; i <= n; i++){
int p = lower_bound(b + 1, b + k + 1, a[i]) - b;
root[i] = modify(root[i - 1], 1, k, p);
}
while(q --){
int u = read(), v = read();
int l = 1, r = v - u + 1, len = v - u + 1;
while(l < r){
int mid = (l + r + 1) >> 1;
int tmp = b[query(root[v], root[u - 1], 1, k, len - mid + 1)];
if(tmp < mid) r = mid - 1;
else l = mid;
}
printf("%d
", l);
}
}
return 0;
}