题目
Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 42132 Accepted: 19801
Case Time Limit: 2000MS
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..N+Q+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.
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
题意
给出一个序列,求这个序列里任意一个区间的最大值减最小值的差。
题解
用的线段树处理。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <string>
#include <set>
#include <cmath>
#include <map>
#include <queue>
#include <sstream>
#include <vector>
#define m0(a) memset(a,0,sizeof(a))
#define mm(a) memset(a,0x3f,sizeof(a))
#define m_1(a) memset(a,-1,sizeof(a))
#define f(i,a,b) for(i = a;i<=b;i++)
#define fi(i,a,b) for(i = a;i>=b;i--)
#define lowbit(a) ((a)&(-a))
#define FFR freopen("data.in","r",stdin)
#define FFW freopen("data.out","w",stdout)
#define SIGN_MAX 0x3f3f3f3f
using namespace std;
#define SIZE 50000
struct Po{
int T_max,T_min;
};
int E;
Po T[SIZE*8+100];
void init(int n){
E = 1;
int i;
while(E<=(n+1))E<<=1;
f(i,1,E*2-1){
T[i].T_max = -SIGN_MAX;
T[i].T_min = SIGN_MAX;
}
}
void Push_up(int t){
T[t].T_max = max(T[t<<1].T_max,T[t<<1|1].T_max);
T[t].T_min = min(T[t<<1].T_min,T[t<<1|1].T_min);
}
void aP(int t,int k){
for(T[t+=E].T_max = k,T[t].T_min = k,t>>=1;t;t>>=1)
Push_up(t);
}
int query(int L,int R){
L+=E-1;
R+=E+1;
Po tem;
tem.T_max = -SIGN_MAX;
tem.T_min = SIGN_MAX;
for(;L^R^1;L>>=1,R>>=1){
if(~L&1){
if(T[L^1].T_max>tem.T_max)
tem.T_max = T[L^1].T_max;
if(T[L^1].T_min<tem.T_min)
tem.T_min = T[L^1].T_min;
}
if(R&1){
if(T[R^1].T_max>tem.T_max)
tem.T_max = T[R^1].T_max;
if(T[R^1].T_min<tem.T_min)
tem.T_min = T[R^1].T_min;
}
}
return tem.T_max-tem.T_min;
}
int main()
{
//ios_base::sync_with_stdio(false); cin.tie(0);
int n,m;
scanf("%d%d",&n,&m);
int i,j;
init(n);
f(i,1,n){
int a;
scanf("%d",&a);
aP(i,a);
}
f(i,1,m){
int L,R;
scanf("%d%d",&L,&R);
printf("%d\n",query(L,R));
}
return 0;
}