题意:求区间中最大的x,满足大于等于x的数量大于等于x
区间数量必须大于等于x,那很明显x一定是小于等于区间长度嘛,二分区间长度就可以了,然后就是找第k大,第k大可以由第len-k+1小解决。
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<cmath>
#include<map>
#include<string>
#include<queue>
#include<stack>
#include<bitset>
#include<list>
#include<set>
#include<utility>
#include<functional>
#include<iomanip>
#define IO ios::sync_with_stdio(false)
#define eps 1e-7
#define int long long
using namespace std;
struct node
{
int ls,rs,sum;
}t[100005*23];
int a[100005],b[100005],n,q,rt[100005],cnt,len;
void upd(int &o,int pre,int l,int r,int pos,int val)
{
o=++cnt;
t[o]=t[pre];
t[o].sum+=val;
if(l==r)
{
return;
}
int mid=l+r>>1;
if(pos<=mid)
{
upd(t[o].ls,t[pre].ls,l,mid,pos,val);
}
else
{
upd(t[o].rs,t[pre].rs,mid+1,r,pos,val);
}
}
int ask(int o,int pre,int l,int r,int k)
{
if(l==r)return l;
int x=t[t[o].ls].sum-t[t[pre].ls].sum;
int mid=l+r>>1;
if(k<=x)
{
return ask(t[o].ls,t[pre].ls,l,mid,k);
}
else
{
return ask(t[o].rs,t[pre].rs,mid+1,r,k-x);
}
}
signed main()
{
IO;
//freopen("1111.txt","w",stdout);
while(cin>>n>>q)
{
cnt=0;
memset(rt,0,sizeof(rt));
memset(t,0,sizeof(t));
for(int i=1;i<=n;i++)
{
cin>>a[i];
b[i]=a[i];
}
sort(b+1,b+n+1);
len=unique(b+1,b+n+1)-(b+1);
for(int i=1;i<=n;i++)
{
int x=lower_bound(b+1,b+len+1,a[i])-b;
upd(rt[i],rt[i-1],1,len,x,1);
}
int x,y;
for(int i=1;i<=q;i++)
{
cin>>x>>y;
int sum=y-x+1;
int l=0,r=sum;
while(l<r)
{
int mid=l+r+1>>1;
if(b[ask(rt[y],rt[x-1],1,len,sum-mid+1)]>=mid)
{
l=mid;
}
else
{
r=mid-1;
}
}
cout<<l<<endl;
}
}
}