#include<stdio.h>
#include<string.h>
struct node
{
node * pl, * pr;
int left, right;
int mxa, min;
}mem[100000];
int memCount;
int n, q;
int mxa, min;
node * newNode()
{
node * pt=&mem[memCount++];
pt->mxa=-1, pt->min=1000001;
return pt;
}
node * buildTree(int l, int r)
{
node * root=newNode();
root->left=l;
root->right=r;
if(r-l>=1)
{
int mid=(l+r)/2;
root->pl=buildTree(l,mid);
root->pr=buildTree(mid+1,r);
}
return root;
}
void update(node * root, int i, int a)
{
if(root->left==i && root->right==i)
{
root->mxa=a, root->min=a;
return ;
}
if(root->min>a)
root->min=a;
if(root->mxa<a)
root->mxa=a;
if(root->pl->right>=i)
{
update(root->pl,i,a);
}else
{
update(root->pr,i,a);
}
}
void que(node * root, int i, int j)
{
if(root->min>min && root->mxa<mxa)
return;
if(root->left==i && root->right==j)
{
if(mxa<root->mxa)
mxa=root->mxa;
if(min>root->min)
min=root->min;
return;
}
if(root->pl->right>=i)
{
if(root->pl->right>=j)
que(root->pl, i, j);
else
{
int mid=(root->left+root->right)/2;
que(root->pl,i,mid);
que(root->pr,mid+1,j);
}
}else
{
que(root->pr,i,j);
}
}
int main()
{
while(scanf("%d%d", &n, &q)==2)
{
memCount=0;
node * root=buildTree(1, n);
int i, a;
for(i=0;i<n;i++)
{
scanf("%d",&a);
update(root,i+1,a);
}
int x, y;
for(i=0;i<q;i++)
{
scanf("%d%d", &x, &y);
mxa=-1, min=1000001;
que(root,x, y);
printf("%d\n",mxa-min);
}
}
return 0;
}
#include<string.h>
struct node
{
node * pl, * pr;
int left, right;
int mxa, min;
}mem[100000];
int memCount;
int n, q;
int mxa, min;
node * newNode()
{
node * pt=&mem[memCount++];
pt->mxa=-1, pt->min=1000001;
return pt;
}
node * buildTree(int l, int r)
{
node * root=newNode();
root->left=l;
root->right=r;
if(r-l>=1)
{
int mid=(l+r)/2;
root->pl=buildTree(l,mid);
root->pr=buildTree(mid+1,r);
}
return root;
}
void update(node * root, int i, int a)
{
if(root->left==i && root->right==i)
{
root->mxa=a, root->min=a;
return ;
}
if(root->min>a)
root->min=a;
if(root->mxa<a)
root->mxa=a;
if(root->pl->right>=i)
{
update(root->pl,i,a);
}else
{
update(root->pr,i,a);
}
}
void que(node * root, int i, int j)
{
if(root->min>min && root->mxa<mxa)
return;
if(root->left==i && root->right==j)
{
if(mxa<root->mxa)
mxa=root->mxa;
if(min>root->min)
min=root->min;
return;
}
if(root->pl->right>=i)
{
if(root->pl->right>=j)
que(root->pl, i, j);
else
{
int mid=(root->left+root->right)/2;
que(root->pl,i,mid);
que(root->pr,mid+1,j);
}
}else
{
que(root->pr,i,j);
}
}
int main()
{
while(scanf("%d%d", &n, &q)==2)
{
memCount=0;
node * root=buildTree(1, n);
int i, a;
for(i=0;i<n;i++)
{
scanf("%d",&a);
update(root,i+1,a);
}
int x, y;
for(i=0;i<q;i++)
{
scanf("%d%d", &x, &y);
mxa=-1, min=1000001;
que(root,x, y);
printf("%d\n",mxa-min);
}
}
return 0;
}