题目描述
The h-index of an author is the largest where he has at least papers with citations not less than .
Bobo has published n papers with citations respectively.
One day, he raises q questions. The i-th question is described by two integers li and ri, asking the h-index of Bobo if has only published papers with citations .
The input consists of several test cases and is terminated by end-of-file.
The first line of each test case contains two integers and .
The second line contains n integers .
The -th of last lines contains two integers and .
For each question, print an integer which denotes the answer.
Constraint
- 1≤≤105
- 1≤≤n
- 1≤≤≤n
- The sum of does not exceed 250,000.
- The sum of does not exceed 250,000.
题解
给定序列a, 在指定区间中找到最大的数字h,使其满足在a[L] ~ a[R]范围内大于等于h的数字不少于h个。
需要涉及区间内有序的问题,可以想到用主席树来做。
二分枚举h,用主席树查找在区间内大于等于h的数字个数是否大于等于h.
(代码借鉴学长lcy大佬,lcytql)
#include<bits/stdc++.h>
using namespace std;
const long long maxn=1e6+10;
struct node{
int sum;
int l,r;
}tree[maxn*30];
void reset(int x){
//这个函数真的 女少 啊,把0节点直接代替初始空线段树所有的节点
tree[x].sum = 0;
tree[x].l = tree[x].r = 0;
}
int root[maxn], tot;
int n,q;
int build(int l, int r, int old, int x){
tot++;
int temp = tot;
tree[tot] = tree[old];
tree[tot].sum++;
if(l==r) return temp;
int mid = (l+r)>>1;
if(x<=mid)
tree[temp].l=build(l, mid, tree[old].l,x);
else
tree[temp].r=build(mid+1, r, tree[old].r, x);
return temp;
}
int query(int l, int r, int lrt, int rrt, int x){
if(l==r)
return tree[rrt].sum - tree[lrt].sum;
int mid=(l+r)>>1;
if(x>mid)
return serch(mid+1, r, tree[lrt].r, tree[rrt].r, x);
else{
int rr = tree[rrt].r, lr = tree[lrt].r;
return tree[rr].sum - tree[lr].sum + serch(l, mid, tree[lrt].l, tree[rrt].l, x);
} //如果h在区间mid右边,则大于h的区间仍然在右子树上,搜索右子树。
//否则整个右子树的值都是大于h的一部分,并且在h到mid间也可能存在大于h的数,继续搜索左子树。
}
int solve(int x, int y){
int l, r, mid, ans;
ans = 1;
l = 1;
r = n;
while(l<=r){
mid = (l+r)>>1;
if(query(1, n, root[x-1], root[y], mid) >= mid){
ans = mid;
l = mid + 1;
}else{
r = mid - 1;
}
}
return ans;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
//freopen("test.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(cin>>n>>q){
tot=0;
reset(0);
for(int i=1;i<=n;i++){
int x;
cin>>x;
root[i]=build(1,n,root[i-1],x);
}
for(int i=1;i<=q;i++){
int l,r;
cin >> l >> r;
cout<<solve(l,r)<<endl;
}
}
return 0;
}
来源:CSDN
作者:Irimsky
链接:https://blog.csdn.net/irimsky/article/details/104355293