题目描述
Mario is world-famous plumber. His “burly” figure and amazing jumping ability reminded in our memory. Now the poor princess is in trouble again and Mario needs to save his lover. We regard the road to the boss’s castle as a line (the length is n), on every integer point i there is a brick on height hi. Now the question is how many bricks in [L, R] Mario can hit if the maximal height he can jump is H.
数据范围
- 1 ≤ n , m ≤ 1 0 5 1\leq n,m\leq 10^5 1≤n,m≤105
- The Height of each brick,the range is [ 0 , 1 0 9 ] [0,10^9] [0,109]
- 0 ≤ L ≤ R < n , 0 ≤ H ≤ 1 0 9 0\leq L\leq R < n,0\leq H\leq 10^9 0≤L≤R<n,0≤H≤109
题解
题目大意就是给出一个序列,求区间 [ l , r ] [l,r] [l,r]中小于等于 k k k的值有多少个。
用可持久化线段树,第 i i i棵权值线段树的叶节点 j j j维护前 i i i个值中等于 j j j的值的数量。区间查询 [ l , r ] [l,r] [l,r]时用第 r r r棵线段树的值减去第 l − 1 l-1 l−1棵线段树的值即可。
但如果只是这样做的话就会MLE,因为此时的空间复杂度为 O ( n l o g 1 0 9 ) O(nlog10^9) O(nlog109)。我们可以离散化一下,空间复杂度就变为 O ( n l o g n ) O(nlogn) O(nlogn),这样就不会TLE了。
code
#include<bits/stdc++.h>
using namespace std;
int t,n,m,tot,a[100005],num[100005],rt[100005];
struct node{
int lc,rc,s;
}tr[2000005];
void ch(int &r1,int r2,int l,int r,int v){
r1=++tot;
tr[r1]=tr[r2];
if(l==r){
++tr[r1].s;return;
}
int mid=(l+r)/2;
if(v<=mid) ch(tr[r1].lc,tr[r2].lc,l,mid,v);
else ch(tr[r1].rc,tr[r2].rc,mid+1,r,v);
tr[r1].s=tr[tr[r1].lc].s+tr[tr[r1].rc].s;
}
int find(int r1,int r2,int l,int r,int x,int y){
if(l>=x&&r<=y){
return tr[r2].s-tr[r1].s;
}
if(l>y||r<x) return 0;
if(l==r) return 0;
int mid=(l+r)/2,re=0;
if(x<=mid) re+=find(tr[r1].lc,tr[r2].lc,l,mid,x,y);
if(y>mid) re+=find(tr[r1].rc,tr[r2].rc,mid+1,r,x,y);
return re;
}
int main()
{
scanf("%d",&t);
for(int o=1;o<=t;o++){
tot=0;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);num[i]=a[i];
}
sort(num+1,num+n+1);
int gs=unique(num+1,num+n+1)-num-1;
for(int i=1;i<=n;i++){
a[i]=lower_bound(num+1,num+gs+1,a[i])-num;
ch(rt[i],rt[i-1],1,n,a[i]);
}
for(int i=1;i<=n;i++){
ch(rt[i],rt[i-1],1,gs,a[i]);
}
printf("Case %d:\n",o);
for(int i=1,a,b,c;i<=m;i++){
scanf("%d%d%d",&a,&b,&c);++a;++b;
c=upper_bound(num+1,num+gs+1,c)-num-1;
printf("%d\n",find(rt[a-1],rt[b],1,gs,1,c));
}
}
return 0;
}