nyoj119-士兵杀敌(三)(线段树,最大最小值)

题目来源:http://acm.nyist/problem.php?pid=119

题意

中文题意。。。

思路

利用二叉堆的特点,写二叉搜索树(线段树),但貌似耗时比RMQ长。
并且还超时了几发,对比了两次的代码,发现只是query里多定义了一个变量,而已。。。导致超时。

代码

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1000000;
struct pp
{
    int minn;
    int maxx;
} tree[(maxn<<2)+1];

int n,q,rt;

void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&tree[rt].minn);
        tree[rt].maxx=tree[rt].minn;
    }
    else
    {
        int m=(l+r)/2;
        build(l,m,rt<<1);
        build(m+1,r,(rt<<1)+1);
        tree[rt].minn=min(tree[rt<<1].minn,tree[(rt<<1)+1].minn);
        tree[rt].maxx=max(tree[rt<<1].maxx,tree[(rt<<1)+1].maxx);
    }
}
int maxx,minn;
void query(int l,int r,int L,int R,int rt)
{
    if(l<=L&&R<=r)
    {
        minn=min(minn,tree[rt].minn);
        maxx=max(maxx,tree[rt].maxx);
        return ;
    }
    int m=(L+R)/2;
    if(m>=l)
    {
        query(l,r,L,m,rt<<1);
    }
    if(m+1<=r)
    {
        query(l,r,m+1,R,(rt<<1)+1);
    }
}
int main()
{
    int n,q;
    scanf("%d%d",&n,&q);
    build(1,n,1);
    while(q--)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        maxx=-1,minn=1000000001;
        query(a,b,1,n,1);
        printf("%d\n",maxx-minn);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值