C. Just h-index
The h-index of an author is the largest h where he has at least h papers with citations not less than h.
Bobo has published n papers with citations a1,a2,a3,……,an respectively. One day,he raises q questions. The i-th question is described by two integers l(i) and r(i), asking the h-index of Bobo if has only published papers with citations a(li),a(li+1),……,a(ri).()中为下标。
题意:
题目背景和第A题相近,不同的是 :
A题 第二行依次给出 0 到 n 次项的系数
C题 第二行依次给出 n 个 不同项的次幂,这些幂次可能相同可能不同,然后有 q 个询问,
每个询问 给出一个有区间 [l,r],问每个区间解
思路:
用主席树求区间第K小的结果,二分答案 求解即可
下面用的是kuangbin的主席树模板
Input
(1)
5 3
1 5 3 2 1
1 3
2 4
1 5
(2)
5 6
1 2 3 4 5
1 1
1 2
1 3
1 4
1 5
3 5
(3)
5 5
5 5 5 5 5
1 5
2 5
3 5
4 5
5 5
output
(1)
2
2
2
(2)
1
1
2
2
3
3
(3)
5
4
3
2
1
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 100010;
const int M = MAXN * 30;
int n,q,m,tot;
int a[MAXN], t[MAXN];
int T[M], lson[M], rson[M], c[M];
void Init_hash()
{
for(int i = 1; i <= n;i++)
t[i] = a[i];
sort(t+1,t+1+n);
m = unique(t+1,t+1+n)-t-1;
}
int build(int l,int r)
{
int root = tot++;
c[root] = 0;
if(l != r)
{
int mid = (l+r)>>1;
lson[root] = build(l,mid);
rson[root] = build(mid+1,r);
}
return root;
}
int hash(int x)
{
return lower_bound(t+1,t+1+m,x) - t;
}
int update(int root,int pos,int val)
{
int newroot = tot++, tmp = newroot;
c[newroot] = c[root] + val;
int l = 1, r = m;
while(l < r)
{
int mid = (l+r)>>1;
if(pos <= mid)
{
lson[newroot] = tot++; rson[newroot] = rson[root];
newroot = lson[newroot]; root = lson[root];
r = mid;
}
else
{
rson[newroot] = tot++; lson[newroot] = lson[root];
newroot = rson[newroot]; root = rson[root];
l = mid+1;
}
c[newroot] = c[root] + val;
}
return tmp;
}
int query(int left_root,int right_root,int k)
{
int l = 1, r = m;
while( l < r)
{
int mid = (l+r)>>1;
if(c[lson[left_root]]-c[lson[right_root]] >= k )
{
r = mid;
left_root = lson[left_root];
right_root = lson[right_root];
}
else
{
l = mid + 1;
k -= c[lson[left_root]] - c[lson[right_root]];
left_root = rson[left_root];
right_root = rson[right_root];
}
}
return l;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(scanf("%d%d",&n,&q) == 2)
{
tot = 0;
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]);
Init_hash();
T[n+1] = build(1,m);
for(i = n;i ;i--)
{
int pos = hash(a[i]);
T[i] = update(T[i+1],pos,1);
}
while(q--)
{
int l,r,k;
scanf("%d%d",&l,&r);
int ll = 1,rr = r - l + 2; //答案的范围是 1 ~ r-l+1
while(ll<rr) {
int mid = ll + rr >> 1;
int w = t[query(T[l],T[r+1],r-l+1-mid+1)]; // 求区间[l,r]第k小 (k=r-l+1-mid+1)
//cout<<ll<<" "<<rr<<" "<<mid<<" "<<w<<endl;
if(w >= mid ) ll = mid + 1; // 如果去年第 k 小 w >= mid,则mid满足条件,ll 调整为 mid + 1
else rr = mid; //mid 不符合 条件
}
printf("%d\n",rr-1);//最后 ll == rr,rr 为 答案加一
}
}
return 0;
}