码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3264 Balanced Lineup 【线段树】+【单点更新】

时间:2014-07-14 12:44:18      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:poj3264

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 32778   Accepted: 15425
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 <stdio.h>
#define maxn 200002
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1

struct Node{
	int min, max;
} tree[maxn << 2];
int maxAns, minAns;

int maxVal(int a, int b)
{
	return a > b ? a : b;
}

int minVal(int a, int b)
{
	return a < b ? a : b;
}

void build(int l, int r, int rt)
{
	if(l == r){
		scanf("%d", &tree[rt].min);
		tree[rt].max = tree[rt].min;
		return;
	}
	
	int mid = (l + r) >> 1;
	build(lson);
	build(rson);
	
	tree[rt].max = maxVal(tree[rt << 1].max, tree[rt << 1 | 1].max);
	tree[rt].min = minVal(tree[rt << 1].min, tree[rt << 1 | 1].min);
}

void query(int left, int right, int l, int r, int rt)
{
	if(left == l && right == r){
		if(tree[rt].max > maxAns) maxAns = tree[rt].max;
		if(minAns > tree[rt].min) minAns = tree[rt].min;
		return;
	}
	
	int mid = (l + r) >> 1;
	if(right <= mid) query(left, right, lson);
	else if(left > mid) query(left, right, rson);
	else{
		query(left, mid, lson);
		query(mid + 1, right, rson);
	}
}

int main()
{
	int n, q, i, a, b;
	scanf("%d%d", &n, &q);
	
	build(1, n, 1);
	
	while(q--){
		scanf("%d%d", &a, &b);
		maxAns = 1; minAns = 1000000;
		query(a, b, 1, n, 1);
		printf("%d\n", maxAns - minAns);
	}
	
	return 0;
}


POJ3264 Balanced Lineup 【线段树】+【单点更新】,布布扣,bubuko.com

POJ3264 Balanced Lineup 【线段树】+【单点更新】

标签:poj3264

原文地址:http://blog.csdn.net/chang_mu/article/details/37744321

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!