【BZOJ】1636: [Usaco2007 Jan]Balanced Lineup(rmq+树状数组)

http://www.lydsy.com/JudgeOnline/problem.php?id=1636

(我是不会说我看不懂题的)

裸的rmq。。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define for1(i,a,n) for(int i=(a);i<=(n);++i)
#define for2(i,a,n) for(int i=(a);i<(n);++i)
#define for3(i,a,n) for(int i=(a);i>=(n);--i)
#define for4(i,a,n) for(int i=(a);i>(n);--i)
#define CC(i,a) memset(i,a,sizeof(i))
#define read(a) a=getint()
#define print(a) printf("%d", a)
#define dbg(x) cout << #x << " = " << x << endl
#define printarr(a, n, m) rep(aaa, n) { rep(bbb, m) cout << a[aaa][bbb]; cout << endl; }
inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; }
inline const int max(const int &a, const int &b) { return a>b?a:b; }
inline const int min(const int &a, const int &b) { return a<b?a:b; }

const int N=50005;
int mx[N], n, q, a[N], mn[N];
void update(int x, int c) { for(; x<=n; x+=x&-x) mx[x]=max(c, mx[x]), mn[x]=min(c, mn[x]); }
int ask(int l, int r) {
	int x=0, y=~0u>>1;
	while(l<=r) {
		x=max(x, a[r]); y=min(y, a[r]);
		for(--r; r-l>=(r&-r); r-=r&-r)
			x=max(mx[r], x), y=min(mn[r], y);
	}
	return x-y;
}

int main() {
	read(n); read(q);
	CC(mn, 0x7f);
	for1(i, 1, n) { read(a[i]); update(i, a[i]); }
	int l, r;
	while(q--) {
		read(l); read(r);
		printf("%d\n", ask(l, r));
	}
	return 0;
}

 

 


 

 

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

6 3 1 7 3 4 2 5 1 5 4 6 2 2

Sample Input

* 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 Output


6
3
0

HINT

Source

posted @ 2014-09-03 05:41  iwtwiioi  阅读(243)  评论(0编辑  收藏  举报