您的位置:首页 > 其它

HDU4417 主席树入门2

2016-11-01 20:10 197 查看
Description

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

这个题和上个题差不多…

但是有不少需要以后写主席树注意的事情

第一个是查询的时候注意lowerbound的问题

它会返回第一个不比他小的

upperbound返回第一个比他大的

记住….

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<memory.h>
using namespace std;
int shuru[100001],tu[100001],zuo[2000001],you[2000001],su[2000001],shu[100001],tou;
int gengxin(int shangyike,int weizhi,int zo,int yo)
{
int xianzai=++tou;
if(zo==yo)
{
su[xianzai]=su[shangyike]+1;
return xianzai;
}
int mid=(zo+yo)/2;
if (weizhi <= mid)
{
you[xianzai] = you[shangyike];
zuo[xianzai] = gengxin(zuo[shangyike], weizhi, zo, mid);
}
else
{
you[xianzai] = gengxin(you[shangyike], weizhi, mid + 1, yo);
zuo[xianzai] = zuo[shangyike];
}
su[xianzai] = su[zuo[xianzai]] + su[you[xianzai]];
return xianzai;
}
int wen(int qian, int hou, int zo, int yo, int k)
{
if(yo<=k)return su[hou]-su[qian];
else if(zo>k)return 0;
else
{
int mid=(zo+yo)/2;
int zoz=wen(zuo[qian],zuo[hou],zo,mid,k);
int yoy=wen(you[qian],you[hou],mid+1,yo,k);
return zoz+yoy;
}
}
int main()
{
int T;
int u=0;
cin>>T;
while(T--)
{
tou=0;
memset(tu,0,sizeof(tu));
memset(zuo,0,sizeof(zuo));
memset(you,0,sizeof(you));
memset(su,0,sizeof(su));
memset(shu,0,sizeof(shu));
int n,m;
cin>>n>>m;
for(int a=1;a<=n;a++)
{
scanf("%d",&shuru[a]);
tu[a]=shuru[a];
}
sort(tu+1,tu+n+1);
printf("Case %d:\n",++u);
int lisa=unique(tu+1,tu+n+1)-tu-1;
//shu[0]=jianli(1,lisa);
int q,w,e;
for(int a=1;a<=n;a++)
{
int weizhi=lower_bound(tu+1,tu+lisa+1,shuru[a])-tu;
shu[a]=gengxin(shu[a-1],weizhi,1,lisa);
}
while (m--)
{
int q, w, e;
cin >> q >> w >> e;
q++,w++;
e=upper_bound(tu+1,tu+lisa+1,e)-tu-1;
cout << wen(shu[q-1], shu[w], 1, lisa, e) << endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: