给你一个长度为n的序列a(1=<a[i]<=n),m次询问,每次求(l , r)区间内最大的h,使得至少h个数的值都大于等于h。
莫队+树状数组维护前缀和+二分查询。
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+100;
struct node{
int l,r,id;
}s[maxn];
int n,m,a[maxn],sum[maxn],ans[maxn];
int tot;
int lowbit(int x){return x&(-x);}
int update(int pos,int val)
{
while(pos<=n)
{
sum[pos]+=val;
pos+=lowbit(pos);
}
}
int query(int pos)
{
int ans=0;
while(pos>0)
{
ans+=sum[pos];
pos-=lowbit(pos);
}
return ans;
}
bool check(int x)
{
int num=tot-query(x-1);
return num>=x;
}
int solve()
{
int l=1,r=n;
while(l<r-1)
{
int mid=(l+r)>>1;
if(check(mid))
l=mid;
else r=mid;
}
int k=l;
if(check(r))
k=r;
return k;
}
int t,block[maxn];
bool cmp(const node &a,const node &b)
{
if(block[a.l]==block[b.l]) return a.r<b.r;
return block[a.l]<block[b.l];
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&s[i].l,&s[i].r);
s[i].id=i;
}
t=sqrt(n);
for(int i=1;i<=n;i++)
block[i]=(i-1)/t;
sort(s+1,s+m+1,cmp);
//memset(sum,0,sizeof sum);
for(int i=0;i<=n;i++)
sum[i]=0;
int l=1,r=1;
update(a[1],1);
tot=1;
for(int i=1;i<=m;i++)
{
while(l<s[i].l)
{
update(a[l],-1);
l++;
tot--;
}
while(l>s[i].l)
{
l--;
update(a[l],1);
tot++;
}
while(r<s[i].r)
{
r++;
update(a[r],1);
tot++;
}
while(r>s[i].r)
{
update(a[r],-1);
r--;
tot--;
}
ans[s[i].id]=solve();
}
for(int i=1;i<=m;i++)
printf("%d\n",ans[i]);
}
return 0;
}