您的位置:首页 > 其它

hdu4417:线段树单点更新区间求和,离线 Super Mario

2016-08-07 19:14 246 查看
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

思路:

离线操作!!!

将原有高度和每次查询的高度分别排序,然后每次将比此次查询小的高度的砖块插入线段树中,是的现有线段树中的所有位置的高度均小于等于要查询的高度,然后查询此区间内有多少个已插入的点;

#include <cstdio>
#include <cstring>
#include <algorithm>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int maxn=1e5+9;
struct node
{
int val,pos;
} no[maxn];
struct que
{
int L,R,pos;
long long H;
} qu[maxn];
int ans[maxn],cnt[maxn<<2];
int cmp1(node a,node b)
{
return a.val<b.val;
}
int cmp2(que a,que b)
{
return a.H<b.H;
}
void update(int pos,int l,int r,int rt)
{
if(l==r)
{
cnt[rt]++;
return;
}
int m=l+r>>1;
if(pos<=m) update(pos,lson);
else update(pos,rson);
cnt[rt]=cnt[rt<<1]+cnt[rt<<1|1];
}
int query(int L,int R,int l,int r,int rt)
{
if(L==l&&R==r)
return cnt[rt];
int m=l+r>>1;
if(R<=m) return query(L,R,lson);
else if(L>m) return query(L,R,rson);
else return query(L,m,lson)+query(m+1,R,rson);
}
int main()
{
int t;
scanf("%d",&t);
for(int ase=1; ase<=t; ase++)
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
{
scanf("%d",&no[i].val);
no[i].pos=i;
}
for(int i=0; i<m; i++)
{
qu[i].pos=i;
scanf("%d%d%I64d",&qu[i].L,&qu[i].R,&qu[i].H);
}
sort(no,no+n,cmp1);
sort(qu,qu+m,cmp2);
memset(cnt,0,sizeof cnt);
int j=0;
for(int i=0; i<m; i++)
{
while(no[j].val<=qu[i].H&&j<n)
update(no[j++].pos,0,n-1,1);
ans[qu[i].pos]=query(qu[i].L,qu[i].R,0,n-1,1);
}
printf("Case %d:\n",ase);
for(int i=0; i<m; i++)
printf("%d\n",ans[i]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: