Balanced Lineup 【线段树】

题目链接POJ-3264

[kuangbin带你飞]专题七 线段树

题目描述

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.


思路

区间查询最大最小,可以用RMQ也可以用线段树;

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <cstdio>
using namespace std;

#define MAX 50050
#define INF 0x3f3f3f3f

struct Node{
int l, r, Max, Min;
}tree[MAX * 4];

void push_up(int k)
{
tree[k].Max = max(tree[k<<1].Max, tree[k<<1|1].Max);
tree[k].Min = min(tree[k<<1].Min, tree[k<<1|1].Min);
}

void build(int k, int l, int r)
{
tree[k].l = l, tree[k].r = r;
if(l == r)
{
scanf("%d", &tree[k].Max);
tree[k].Min = tree[k].Max;
}
else
{
int mid = (l + r) >> 1;
build(k<<1, l, mid);
build(k<<1|1, mid+1, r);
push_up(k);
}
}

int query_Max(int k, int l, int r)
{
int L = tree[k].l, R = tree[k].r;
if(l <= L && R <= r)
{
return tree[k].Max;
}
else
{
int tmp_max = -INF;
int mid = (L + R) >> 1;
if(l <= mid)
tmp_max = max(tmp_max, query_Max(k<<1, l, r));
if(mid < r)
tmp_max = max(tmp_max, query_Max(k<<1|1, l, r));
return tmp_max;
}
}

int query_Min(int k, int l, int r)
{
int L = tree[k].l, R = tree[k].r;
if(l <= L && R <= r)
{
return tree[k].Min;
}
else
{
int tmp_min = INF;
int mid = (L + R) >> 1;
if(l <= mid)
tmp_min = min(tmp_min, query_Min(k<<1, l, r));
if(mid < r)
tmp_min = min(tmp_min, query_Min(k<<1|1, l, r));
return tmp_min;
}
}

int main()
{
int n, m;
scanf("%d %d", &n, &m);
build(1, 1, n);
for(int i = 1; i<=m; i++)
{
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n",query_Max(1, x, y) - query_Min(1, x, y));
}
return 0;
}
-------------本文结束,感谢您的阅读!-------------