POJ 3264 Balanced Lineup
http://poj.org/problem?id=3264
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
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 <stdio.h> #include <cstdio> #include <algorithm> #include <string> using namespace std; const int inf = 1e8 + 10; const int maxn = 1e6 + 10; int N, M; int Min, Max; int a[maxn]; struct Node{ int l; int r; int maxx; int minn; }node[maxn]; void Build(int i, int l, int r) { node[i].l = l; node[i].r = r; if(l == r) { node[i].maxx = node[i].minn = a[l]; return ; } int mid = (l + r) / 2; Build(i * 2, l, mid); Build(i * 2 + 1, mid + 1, r); node[i].maxx = max(node[i * 2].maxx, node[i * 2 + 1].maxx); node[i].minn = min(node[i * 2].minn, node[i * 2 + 1].minn); } void query(int i, int l, int r) { if(node[i].maxx <= Max && node[i].minn >= Min) return; if(node[i].l == l && node[i].r == r) { Max = max(Max, node[i].maxx); Min = min(Min, node[i].minn); return ; } int mid = (node[i].l + node[i].r) / 2; if(r <= mid) query(i * 2, l, r); else if(l > mid) query(i * 2 + 1, l, r); else { query(i * 2, l, mid); query(i * 2 + 1, mid + 1, r); } } int main() { while(~scanf("%d%d", &N, &M)) { for(int i = 1; i <= N; i ++) scanf("%d", &a[i]); Build(1, 1, N); while(M --) { int st, en; scanf("%d%d", &st, &en); Min = inf, Max = -inf; query(1, st, en); printf("%d\n", Max - Min); } } return 0; }
线段树求区间最大值和最小值的差 会建线段树了 有 1.. 开心 突然想起来今天的 Leetcode 还没写
许嵩演唱会的票子没抢到 呜呜呜
