POJ 3264

题目链接:http://poj.org/problem?id=3264

——————————————————————————————————————————

题目简述:题意:给出一个长度为N<=10^6的数字串和M<=10^5个操作。操作有一种:求出[L, R]范围中,最大值与最小值的差值

——————————————————————————————————————————

题目关键字:线段树

——————————————————————————————————————————

题目思路:简单的线段树题目。其中find返回值是tree型(因为返回的是一个类型,无所谓局部变量的问题)

——————————————————————————————————————————

源代码:

#include<stdio.h>

struct tree
{
    int max;
    int min;
    int left;
    int right;       
}tree[3000000];

int n = 0;
int cow[500010];

int mmax(int a,int b)
{
   if(a>b)  return a;
   else return b;    
}

int mmin(int a,int b)
{
   if(a>b)  return b;
   else return a;
}

void init(int cur,int l,int r)
{ 
    int m = (l+r)/2;
    
    tree[cur].left = l;
    tree[cur].right = r;
    
    if(l == r)
    {
        tree[cur].max = cow[l];
        tree[cur].min = cow[l];    
    }
    else
    {
        init(cur*2,l,m);
        init(cur*2+1,m+1,r);
        
        tree[cur].max = mmax(tree[cur*2].max,tree[cur*2+1].max);
        tree[cur].min = mmin(tree[cur*2].min,tree[cur*2+1].min);
    }
}

struct tree find(int cur,int a,int b)
{
     struct tree l,r,ans;
     
     if(a == tree[cur].left && b == tree[cur].right)
        return tree[cur];
        
     else
     {
        int m = (tree[cur].left+tree[cur].right)/2;
       
        if(a>m) return find(cur*2+1,a,b);
        else if(b<=m) return find(cur*2,a,b);
             else 
             {
                  l = find(cur*2,a,m);
                  r = find(cur*2+1,m+1,b);
                  ans.max = mmax(l.max,r.max);
                  ans.min = mmin(l.min,r.min);
                  return ans;
             }
     }         
}

int main()
{
    int i = 0,q = 0;
    int a = 0,b = 0;
    struct tree ans;
    
    scanf("%d%d",&n,&q);
    for(i = 1;i<=n;i++)
      scanf("%d",&cow[i]);
    
    init(1,1,n);
    
    for(i = 0;i<q;i++)
    {
       scanf("%d%d",&a,&b);
       ans = find(1,a,b);
       printf("%d\n",ans.max-ans.min);
    }


    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值