HDU4417 Super Mario(主席树)

HDU4417 Super Mario

题目描述

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.

数据范围
  • 1 ≤ n , m ≤ 1 0 5 1\leq n,m\leq 10^5 1n,m105
  • The Height of each brick,the range is [ 0 , 1 0 9 ] [0,10^9] [0,109]
  • 0 ≤ L ≤ R < n , 0 ≤ H ≤ 1 0 9 0\leq L\leq R < n,0\leq H\leq 10^9 0LR<n,0H109

题解

题目大意就是给出一个序列,求区间 [ l , r ] [l,r] [l,r]中小于等于 k k k的值有多少个。

可持久化线段树,第 i i i棵权值线段树的叶节点 j j j维护前 i i i个值中等于 j j j的值的数量。区间查询 [ l , r ] [l,r] [l,r]时用第 r r r棵线段树的值减去第 l − 1 l-1 l1棵线段树的值即可。

但如果只是这样做的话就会MLE,因为此时的空间复杂度为 O ( n l o g 1 0 9 ) O(nlog10^9) O(nlog109)。我们可以离散化一下,空间复杂度就变为 O ( n l o g n ) O(nlogn) O(nlogn),这样就不会TLE了。

code

#include<bits/stdc++.h>
using namespace std;
int t,n,m,tot,a[100005],num[100005],rt[100005];
struct node{
    int lc,rc,s;
}tr[2000005];
void ch(int &r1,int r2,int l,int r,int v){
    r1=++tot;
    tr[r1]=tr[r2];
    if(l==r){
        ++tr[r1].s;return;
    }
    int mid=(l+r)/2;
    if(v<=mid) ch(tr[r1].lc,tr[r2].lc,l,mid,v);
    else ch(tr[r1].rc,tr[r2].rc,mid+1,r,v);
    tr[r1].s=tr[tr[r1].lc].s+tr[tr[r1].rc].s;
}
int find(int r1,int r2,int l,int r,int x,int y){
    if(l>=x&&r<=y){
        return tr[r2].s-tr[r1].s;
    }
    if(l>y||r<x) return 0;
    if(l==r) return 0;
    int mid=(l+r)/2,re=0;
    if(x<=mid) re+=find(tr[r1].lc,tr[r2].lc,l,mid,x,y);
    if(y>mid) re+=find(tr[r1].rc,tr[r2].rc,mid+1,r,x,y);
    return re;
}
int main()
{
    scanf("%d",&t);
    for(int o=1;o<=t;o++){
        tot=0;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);num[i]=a[i];
    }
        sort(num+1,num+n+1);
        int gs=unique(num+1,num+n+1)-num-1;
        for(int i=1;i<=n;i++){
            a[i]=lower_bound(num+1,num+gs+1,a[i])-num;
            ch(rt[i],rt[i-1],1,n,a[i]);
        }
        for(int i=1;i<=n;i++){
            ch(rt[i],rt[i-1],1,gs,a[i]);
        }
        printf("Case %d:\n",o);
        for(int i=1,a,b,c;i<=m;i++){
            scanf("%d%d%d",&a,&b,&c);++a;++b;
            c=upper_bound(num+1,num+gs+1,c)-num-1;
            printf("%d\n",find(rt[a-1],rt[b],1,gs,1,c));
        }
    }
    return 0;
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值