http://poj.org/problem?id=3264

简单的线段树,写这个代码的目的是为了写一个模板,同时也学习一些用全局变量的巧妙用法;

:用一个函数求出两个需要值

这是我的代码

#include<stdio.h>
 #include<stdlib.h>
 #include<string.h>
 #include<math.h>
 #include<iostream>
 #include<algorithm>
 using namespace std;


 #define sizen 220000
 int Max,Min;
 struct ele
 {
     int left;
     int right;
     int maxn;
     int minn;
 }p[sizen*4];
 int arr[sizen];


 void build(int L,int R,int step)
 {
     p[step].left=L;
     p[step].right=R;
     if(L==R)
         p[step].maxn=p[step].minn=arr[L];
     else
     {
         int Mid=(L+R)>>1;
         build(L,Mid,2*step);
         build(Mid+1,R,2*step+1);
         p[step].maxn=max(p[2*step].maxn,p[2*step+1].maxn);
         p[step].minn=min(p[2*step].minn,p[2*step+1].minn);
     }
 }


 void view(int x,int y,int step)
 {
     if(p[step].left==x&&p[step].right==y)
     {
         Max=max(Max,p[step].maxn);
         Min=min(Min,p[step].minn);
     }
     else
    {
         int Mid=(p[step].left+p[step].right)>>1;
         if(y<=Mid)
             view(x,y,2*step);
         else
         if(x>=Mid+1)
             view(x,y,2*step+1);
         else
         {
             view(x,Mid,2*step);
             view(Mid+1,y,2*step+1);
         }
    }
 }


 int main()
 {
     int N,Q;
     int i;
     int x,y;
     while(scanf("%d%d",&N,&Q)!=EOF)
     {
         for(i=1;i<=N;i++)
             scanf("%d",&arr[i]);
         build(1,N,1);
         while(Q--)
         {
             Max=0;
             Min=99999999;
             scanf("%d%d",&x,&y);
             view(x,y,1);
             printf("%d\n",Max-Min);
         }
     }
     return 0;
 }