The hh-index of an author is the largest hh where he has at least hh papers with citations not less than hh.
Bobo has published nn papers with citations a1,a2,…,ana1,a2,…,an respectively.
One day, he raises qq questions. The ii-th question is described by two integers lili and riri, asking the hh-index of Bobo if has only published papers with citations ali,ali+1,…,ariali,ali+1,…,ari.
Input
The input consists of several test cases and is terminated by end-of-file.
The first line of each test case contains two integers nn and qq.
The second line contains nn integers a1,a2,…,ana1,a2,…,an.
The ii-th of last qq lines contains two integers lili and riri.
Output
For each question, print an integer which denotes the answer.
Constraint
- 1≤n,q≤1051≤n,q≤105
- 1≤ai≤n1≤ai≤n
- 1≤li≤ri≤n1≤li≤ri≤n
- The sum of nn does not exceed 250,000250,000.
- The sum of qq does not exceed 250,000250,000.
Sample Input
5 3
1 5 3 2 1
1 3
2 4
1 5
5 1
1 2 3 4 5
1 5
Sample Output
2
2
2
3
题意:一组长度为n的序列,m次查询。每次查询给出两个数字l和r。询问的是找出最大的数字k,使得l到r之间的数字至少有k个数字大于等于k。
思路很简单,二分答案,主席树上求区间大于等于k的数字个数。
很多题解说的是求区间第k大,其实没有那么麻烦,直接离散化之后二分答案k,求大于等于k的个数就行。根据个数缩短区间。
代码如下:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxx=1e5+100;
struct node{
int l;
int r;
int sum;
}p[maxx*40];
int a[maxx],b[maxx],root[maxx];
int n,m,tot;
/*--------------主席树--------------*/
inline int build(int l,int r)
{
int cur=++tot;
p[cur].sum=0;
if(l==r) return cur;
int mid=l+r>>1;
p[cur].l=build(l,mid);
p[cur].r=build(mid+1,r);
return cur;
}
inline int update(int rot,int pos,int l,int r)
{
int cur=++tot;
p[cur]=p[rot];
p[cur].sum++;
if(l==r) return cur;
int mid=l+r>>1;
if(pos<=mid) p[cur].l=update(p[rot].l,pos,l,mid);
else p[cur].r=update(p[rot].r,pos,mid+1,r);
return cur;
}
inline int query(int lrot,int rrot,int l,int r,int pos)
{
if(l==r) return p[rrot].sum-p[lrot].sum;
int mid=l+r>>1;
int sum=0;
if(pos<=mid) sum=query(p[lrot].l,p[rrot].l,l,mid,pos)+p[p[rrot].r].sum-p[p[lrot].r].sum;
else sum=query(p[lrot].r,p[rrot].r,mid+1,r,pos);
return sum;
}
int main()
{
int l,r;
while(~scanf("%d%d",&n,&m))
{
tot=0;
for(int i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=a[i];
sort(b+1,b+1+n);
int len=unique(b+1,b+1+n)-b-1;//离散化
root[0]=build(1,len);
for(int i=1;i<=n;i++) root[i]=update(root[i-1],lower_bound(b+1,b+1+len,a[i])-b,1,n);
while(m--)
{
scanf("%d%d",&l,&r);
int L=1,R=n,mid,ans;
while(L<=R)
{
mid=L+R>>1;
int zz=query(root[l-1],root[r],1,n,lower_bound(b+1,b+1+len,mid)-b);
if(zz>=mid)
{
ans=mid;
L=mid+1;
}
else R=mid-1;
}
printf("%d\n",ans);
}
}
return 0;
}
努力加油a啊,(o)/~