hdu 4417 Super Mario (线段树+动态数组)

Super Mario

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2685    Accepted Submission(s): 1306


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
 



#include 
#include 
#include 
using namespace std;
const int maxn = 100050;

struct node
{
    int l,r,len;
    int *sub;
} a[maxn*4];
int n,m,b[maxn];

void build(int l,int r,int k)
{
    a[k].l=l,a[k].r=r;
    a[k].sub = new int[r-l+3];
    int cnt=0;
    for(int i=l; i<=r; i++) a[k].sub[cnt++]=b[i];
    a[k].len=cnt;
    sort(a[k].sub,a[k].sub+cnt);
    if(l!=r)
    {
        int mid=(l+r)>>1;
        build(l,mid,2*k);
        build(mid+1,r,2*k+1);
    }
}

int query(int l,int r,int h,int k)
{
    if(a[k].l==l && a[k].r==r)
    {
         int num=upper_bound(a[k].sub,a[k].sub+a[k].len,h)-a[k].sub;
         return num;
    }
    else
    {
        int mid=(a[k].l+a[k].r)>>1;
        if(r<=mid)  return query(l,r,h,2*k);
        else if(l>mid)   return query(l,r,h,2*k+1);
        else  return query(l,mid,h,2*k)+query(mid+1,r,h,2*k+1);

    }
}

void Delete(int l,int r,int k)
{
    delete[] a[k].sub;
    if(l!=r)
    {
        int mid=(l+r)>>1;
        Delete(l,mid,2*k);
        Delete(mid+1,r,2*k+1);
    }
}

int main()
{
    int T,x,y,h;
    scanf("%d",&T);
    for(int co=1; co<=T; co++)
    {
        scanf("%d %d",&n,&m);
        for(int i=1; i<=n; i++)  scanf("%d",&b[i]);
        build(1,n,1);
        printf("Case %d:\n",co);
        for(int i=1; i<=m; i++)
        {
            scanf("%d %d %d",&x,&y,&h);
            printf("%d\n",query(x+1,y+1,h,1));
        }
        Delete(1,n,1);
    }
    return 0;
}


你可能感兴趣的:(线段树)