哈理工OJ 1189 区间最大值 II(线段树【简单】)

24 篇文章 1 订阅
15 篇文章 0 订阅

区间最大值 II
Time Limit: 1000 MS Memory Limit: 65535 K
Total Submit: 485(160 users) Total Accepted: 175(115 users) Rating: Special Judge: No
Description
给一个有n个整数的序列a1, a2, a3, …, an,然后有q个提问,每个提问为两个整数i、j,(i<=j),请你回答,在ai到aj中,最大值是多少。

注意:1 <= n,q <= 100000, ai在int整型表示的范围内。

Input
有多组测试数据。
每组测试数据的第一行为一个整数n,表示有n个数;
第二行为n个整数,表示a1,a2,..an;
第三行为q,表示q个提问。
接下来有q行,每行两个数i, j, (i <= j)。
Output
每组测试数据先输出一行”Case n:”, n从1开始计数;
接下来有q行,每行对应一个提问,每行只有一个整数,为ai到aj间的最大值。

Sample Input
3
1 3 2
2
1 2
2 3
4
1 2 3 4
3
1 2
2 4
1 1
Sample Output
Case 1:
3
3
Case 2:
2
4
1
Hint
题目数据已更新。

本题就是一道简单的线段树题目,个人是在线段树建树的时候就对每个区间的最大值找出来,然后把其输出就OK了。

下面是AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct node
{
    int left,right,val;
} c[300005];

void build_tree(int root,int l,int r)
{
    c[root].left=l;
    c[root].right=r;
    if(c[root].left==c[root].right)
    {
        scanf("%d",&c[root].val);
        return ;
    }
    int mid=(c[root].left+c[root].right)/2;
    build_tree(root*2,l,mid);
    build_tree(root*2+1,mid+1,r);
    c[root].val=max(c[root].val,max(c[root*2].val,c[root*2+1].val));
}

int search_tree(int root,int l,int r)
{
    if(c[root].left==l&&c[root].right==r)
    {
        return c[root].val;
    }
    int mid=(c[root].left+c[root].right)/2;
    int x;
    if(mid<l)
    {
        return x=search_tree(root*2+1,l,r);
    }
    else if(mid>=r)
    {
        return x=search_tree(root*2,l,r);
    }
    else
    {
        int x1=search_tree(root*2,l,mid);
        int x2=search_tree(root*2+1,mid+1,r);
        x=max(x1,x2);
        return x;
    }
}

int main()
{
    int t=0,n,q;
    while(~scanf("%d",&n))
    {
        t++;
        for(int i=0; i<=n; i++)
        {
            c[i].val=0;
        }
        build_tree(1,1,n);
        scanf("%d",&q);
        printf("Case %d:\n",t);
        while(q--)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            int re=search_tree(1,a,b);
            printf("%d\n",re);
        }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值