1. 程式人生 > 其它 >P2880 [USACO07JAN] Balanced Lineup G

P2880 [USACO07JAN] Balanced Lineup G

題面

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 ≤ 180,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.

每天,農夫 John 的 \(n(1\le n\le 5\times 10^4)\) 頭牛總是按同一序列排隊。

有一天, John 決定讓一些牛們玩一場飛盤比賽。他準備找一群在佇列中位置連續的牛來進行比賽。但是為了避免水平懸殊,牛的身高不應該相差太大。John 準備了 \(q(1\le q\le 1.8\times10^5)\)

個可能的牛的選擇和所有牛的身高 \(h_i(1\le h_i\le 10^6,1\le i\le n)\)。他想知道每一組裡面最高和最低的牛的身高差。

輸入格式

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.

第一行兩個數 \(n,q\)

接下來 \(n\) 行,每行一個數 \(h_i\)

再接下來 \(q\) 行,每行兩個整數 \(a\)\(b\),表示詢問第 \(a\) 頭牛到第 \(b\) 頭牛裡的最高和最低的牛的身高差。

輸出格式

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.

輸出共 \(q\) 行,對於每一組詢問,輸出每一組中最高和最低的牛的身高差。

思路

線段樹求RMQ模板題。

程式碼

#include <bits/stdc++.h>
using namespace std;

int n, q, a[1000005];
int maxn[1000005 << 2], minn[1000005 << 2];
bool flag = true;

void pushup(int i) {
	maxn[i] = max(maxn[i << 1], maxn[i << 1 | 1]);
	minn[i] = min(minn[i << 1], minn[i << 1 | 1]);
}

void build(int i, int l, int r) {
	if (l == r) {
		maxn[i] = minn[i] = a[l];
		return;
	}
	int mid = (l + r) >> 1;
	build(i << 1, l, mid);
	build(i << 1 | 1, mid + 1, r);
	pushup(i);
}

int querymax(int L, int R, int l, int r, int i) {
	if (L <= l && r <= R) {
		return maxn[i];
	}
	int mid = (l + r) >> 1;
	int result = INT_MIN;
	if (L <= mid) {
		result = max(result, querymax(L, R, l, mid, i << 1));
	}
	if (R > mid) {
		result = max(result, querymax(L, R, mid + 1, r, i << 1 | 1));
	}
	return result;
}
int querymin(int L, int R, int l, int r, int i) {
	if (L <= l && r <= R) {
		return minn[i];
	}
	int mid = (l + r) >> 1;
	int result = INT_MAX;
	if (L <= mid) {
		result = min(result, querymin(L, R, l, mid, i << 1));
	}
	if (R > mid) {
		result = min(result, querymin(L, R, mid + 1, r, i << 1 | 1));
	}
	return result;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> q;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	build(1, 1, n);
	while(q--){
		int l,r;
		cin>>l>>r;
		cout<<querymax(l,r,1,n,1)-querymin(l,r,1,n,1)<<endl;
	}
	return 0;
}