POJ 3264 线段树

来源:互联网 发布:蚁群算法基本流程图 编辑:程序博客网 时间:2024/03/28 21:52
Balanced Lineup
 

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 andQ.
Lines 2..N+1: Line i+1 contains a single integer that is the height of cowi
Lines N+2..N+Q+1: Two integers A and B (1 ≤ABN), representing the range of cows from A toB 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.

Sample Input

6 31734251 54 62 2

Sample Output

630
线段树大水题
这么简单的题目,比赛的时候居然忘东忘西
受不鸟
题意:
给你N头牛的身高
给你一个范围,输出这个范围内的最高与最矮的差值
代码:
#include <iostream>using namespace std;const int maxn=111111;int sum[maxn<<2];int minn[maxn<<2];#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1int Max,Min;void pushup(int rt){sum[rt]=sum[rt<<1]>sum[rt<<1|1]?sum[rt<<1]:sum[rt<<1|1];minn[rt]=minn[rt<<1]<minn[rt<<1|1]?minn[rt<<1]:minn[rt<<1|1];//cout<<sum[rt]<<' '<<minn[rt]<<endl;}void build(int l,int r,int rt){if(l==r){scanf("%d",&sum[rt]);minn[rt]=sum[rt];return;}int m=(l+r)>>1;build(lson);build(rson);pushup(rt);}void query(int l,int r,int rt,int L,int R)//询问{if(L<=l&&R>=r){if(Max<sum[rt])Max=sum[rt];if(Min>minn[rt])Min=minn[rt];return ;}int m=(l+r)>>1;if(L<=m)query(lson,L,R);if(R>m)query(rson,L,R); }int main(){int t,n,mm,i;int a,b;while(~scanf("%d%d",&n,&mm)){build(1,n,1);while(mm--){scanf("%d%d",&a,&b);Max=0,Min=1111110;query(1,n,1,a,b);cout<<Max-Min<<endl;}}return 0;}

 
原创粉丝点击