nbut线段树专题I - Balanced Lineup

来源:互联网 发布:完美告白知乎 编辑:程序博客网 时间:2024/06/06 02:35

Description

For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

Input

Line 1: Two space-separated integers, N and Q
Lines 2.. N+1: Line i+1 contains a single integer that is the height of cow i
Lines N+2.. NQ+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

Output

Lines 1.. Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

如果不用线段树的话,也可以用rmq来做,既然放在线段树这个专题,就用县吨数了,对,我这里用的是zkw线段树。。。。

#include<stdio.h>
#include<algorithm>
#include<iostream>
#define maxn 50010
using namespace std;
int n,M;
struct node
{
int maxs,mins;
}tree[maxn*3];
void build(int n)
{
for(M=1;M<=n+1;M<<=1);
for(int i=M+1;i<=M+n;i++)
{
scanf("%d",&tree[i].maxs);
tree[i].mins=tree[i].maxs;
}
for(int i=M-1;i;i--)
{
tree[i].maxs=max(tree[i<<1].maxs,tree[i<<1|1].maxs);
tree[i].mins=min(tree[i<<1].mins,tree[i<<1|1].mins);
}
}

void query(int s,int t)
{
int a=-1,b=0x3f3f3f3f;
for(s=s+M-1,t=t+M+1;s^t^1;s>>=1,t>>=1)
{
if(~s&1)
{
a=max(tree[s^1].maxs,a);
b=min(tree[s^1].mins,b);
}
if(t&1)
{
a=max(tree[t^1].maxs,a);
b=min(tree[t^1].mins,b);
}
}
printf("%d\n",a-b);
}

int main()
{
int q;
while(~scanf("%d%d",&n,&q))
{
build(n);
int x,y;
while(q--)
{
scanf("%d%d",&x,&y);
query(x,y);
}
}
return 0;
}


0 0
原创粉丝点击