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.
Input
The first line follows an integer T, the number of test data.
For each test data:
The first line contains two integers n, m (1 <= n <=10^5, 1 <= m <= 10^5), n is the length of the road, m is the number of queries.
Next line contains n integers, the height of each brick, the range is [0, 1000000000].
Next m lines, each line contains three integers L, R,H.( 0 <= L <= R < n 0 <= H <= 1000000000.)
Output
For each case, output "Case X: " (X is the case number starting from 1) followed by m lines, each line contains an integer. The ith integer is the number of bricks Mario can hit for the ith query.
Sample Input
1
10 10
0 5 2 7 5 4 3 8 7 7
2 8 6
3 5 0
1 3 1
1 9 4
0 1 0
3 5 5
5 5 1
4 6 3
1 5 7
5 7 3
Sample Output
Case 1:
4
0
0
3
1
2
0
1
5
1
- 把查询的右端点从小到大排序
- 把砖块按从低到高排序
- 边插入边查询
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<stdio.h>
using namespace std;
int ans[100009];
int c[100009];
int n,m;
struct node{
int v;
int p;
}a[100209];
struct que{
int l,r,h;
int id;
}q[100209];
bool cmp1(node a,node b){
return a.v<b.v;
}
bool cmp2(que c,que d){
return c.h<d.h;
}
void add(int x){
for(;x<=n;x+=x&-x) c[x]+=1;
}
int ask(int x){
int ans=0;
for(;x;x-=x&-x) ans+=c[x];
return ans;
}
int main(){
int ca;
scanf("%d",&ca);
int ct=1;
while(ca--){
memset(c,0,sizeof(c));
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&a[i].v);
a[i].p=i;
}
for(int i=1;i<=m;i++){
int tl,tr,th;
scanf("%d%d%d",&tl,&tr,&th);
q[i].l=tl+1;q[i].r=tr+1;q[i].h=th;
q[i].id=i;
}
sort(a+1,a+n+1,cmp1);
sort(q+1,q+m+1,cmp2);
int j=1;
for(int i=1;i<=m;i++){
// for(int k=1;k<=40;k++) printf("c[%d]:%d\n",k,c[k]);
while(j<=n&&a[j].v<=q[i].h){
// printf("j:%d a[j]p:%d\n",j,a[j].p);
add(a[j].p);
j++;
}
ans[q[i].id]=ask(q[i].r)-ask(q[i].l-1);
}
printf("Case %d:\n",ct++);
for(int i=1;i<=m;i++){
printf("%d\n",ans[i]);
}
}
}