http://www.cnblogs.com/kuangbin/archive/2012/09/23/2699122.html
http://acm.hdu.edu.cn/showproblem.php?pid=4417
Super Mario
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1371 Accepted Submission(s): 665
Problem 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
解析:
题意:给出n个位置的砖块高度,
m组区间以及在该区间可以跳的最大高度,问在该区间可以撞到的砖块数
思路:属于区间查询问题,首先可以将数组进行排序排序然后从小到大开始历遍,避免了重复的情况。
利用线段树或树状数组
另一种解法:二分+划分树http://hi.baidu.com/zyz913614263/item/d38a0a8aa79189fee496e0bb
*/
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include <iostream>
using namespace std;
const int maxn=100000+5;
int n,m;
int ans[maxn];
struct pp1
{
int h;
int id;
}p1[maxn];
struct pp2
{
int r;
int l;
int h;
int id;
}p2[maxn];
int c[maxn];
int lowbit( int x)
{
return x&(-x);
}
int sum(int x)
{
int ret=0;
while(x>0)
{
ret+=c[x];
x-=lowbit(x);
}
return ret;
}
void add(int x,int d)
{
while(x<=n)
{
c[x]+=d;
x+=lowbit(x);
}
}
int cmp1(pp1 a,pp1 b)
{
return a.h<b.h;
}
int cmp2(pp2 a,pp2 b)
{
return a.h<b.h;
}
int main()
{ int T,t;
int i,j;
scanf("%d",&T);
for(t=1;t<=T;t++)
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
{scanf("%d",&p1[i].h);
p1[i].id=i;
}
for(j=1;j<=m;j++)
{
scanf("%d%d%d",&p2[j].l,&p2[j].r,&p2[j].h);
p2[j].l++;
p2[j].r++;
p2[j].id=j;
}
memset(c,0,sizeof(c));
sort(p1+1,p1+n+1,cmp1);
sort(p2+1,p2+m+1,cmp2);
j=1;
i=1;
while(j<=m)
{
while(i<=n)
{if(p1[i].h>p2[j].h)
break;
add(p1[i].id,1);//如果可撞到砖块则更新数组,因为数组已经从小倒排序则可以避免更新重复情况
i++;
}
while(j<=m)
{
if(i<=n&&p1[i].h<=p2[j].h)//如果此时仍然可修改则返回上层继续修改
break;
ans[p2[j].id]=sum(p2[j].r)-sum(p2[j].l-1);//修改完毕之后直接运
j++;
}
}
printf("Case %d:\n",t);
for(i=1;i<=m;i++)
printf("%d\n",ans[i]);
}
//system("pause");
return 0;
}