题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1636

解:线段树裸题(都不用更新。。。st就好了)

程序:

#include<iostream>
#include<cstring>
#include<cstdio>
#define INF 2100000000
using namespace std;
int f1[2000000],f2[2000000],a[1000000],n;
inline int read()
{
  int ef=0; char c;
  while ((c<'0')||(c>'9')) c=getchar();
  while ((c>='0')&&(c<='9')) 
  {
      ef=ef*10+c-'0';
      c=getchar();
  }
  return ef;
}
inline void print(int x)
{
  int cnt=0;
  char q[20];
  if (x==0) putchar('0');
  while (x>0)
  {
    q[++cnt]=x%10+'0';
    x=x/10;
  }
  for (int i=cnt;i>=1;i--) putchar(q[i]);
  putchar('\n');
}
void build1(int root,int nowl,int nowr)
{
  if (nowl==nowr) 
  {
    f1[root]=a[nowl];
    return;
  }
  int mid=(nowl+nowr)/2;
  build1(root*2,nowl,mid);
  build1(root*2+1,mid+1,nowr);
  f1[root]=max(f1[root*2],f1[root*2+1]);
}
void build2(int root,int nowl,int nowr)
{
  if (nowl==nowr) 
  {
    f2[root]=a[nowl];
    return;
  }
  int mid=(nowl+nowr)/2;
  build2(root*2,nowl,mid);
  build2(root*2+1,mid+1,nowr);
  f2[root]=min(f2[root*2],f2[root*2+1]);
}
int query1(int root,int nowl,int nowr,int l,int r)
{
  if ((nowl>r)||(nowr<l)) return 0;
  if ((nowl>=l)&&(nowr<=r)) return f1[root];
  int mid=(nowl+nowr)/2;
  return (max(query1(root*2,nowl,mid,l,r),query1(root*2+1,mid+1,nowr,l,r)));
}
int query2(int root,int nowl,int nowr,int l,int r)
{
  if ((nowl>r)||(nowr<l)) return INF;
  if ((nowl>=l)&&(nowr<=r)) return f2[root];
  int mid=(nowl+nowr)/2;
  return (min(query2(root*2,nowl,mid,l,r),query2(root*2+1,mid+1,nowr,l,r)));
}
int main()
{
  int q1;
  n=read(); q1=read();
  for (int i=1;i<=n;i++) a[i]=read();
  build1(1,1,n);build2(1,1,n);
  int x1,y1;
  for (int i=1;i<=q1;i++)
  {
      x1=read(); y1=read();
      print(query1(1,1,n,x1,y1)-query2(1,1,n,x1,y1));
  }
  return 0;
}

 

posted on 2017-04-03 01:06  nhc2014  阅读(175)  评论(0编辑  收藏  举报