poj3264 Balanced Lineup——线段树
发布日期:2021-06-29 05:37:50 浏览次数:3 分类:技术文章

本文共 2443 字,大约阅读时间需要 8 分钟。

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 54929   Accepted: 25726
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 31734251 54 62 2

Sample Output

630
题意:给n个数字,q次询问,每次询问一个区间[a, b]内的最大值与最小值之差。

解析:很裸的一个线段树,而且不需要建好树之后都不用更新,只需查询。维护区间内的最大值和最小值即可。

代码:

#include 
#include
#include
using namespace std;#define N 50001struct node { int l, r; int Max, Min;};node a[N*4];void push_up(int i){ a[i].Max = max(a[i<<1].Max, a[i<<1|1].Max); a[i].Min = min(a[i<<1].Min, a[i<<1|1].Min);}void build(int l, int r, int i){ a[i].l = l; a[i].r = r; if(l == r){ int x; scanf("%d", &x); a[i].Max = a[i].Min = x; return; } int mid = (l + r) >> 1; build(l, mid, i<<1); build(mid+1, r, i<<1|1); push_up(i);}void query(int l, int r, int i, int &Max, int &Min){ if(a[i].l == l && a[i].r == r){ Max = a[i].Max; Min = a[i].Min; return; } int mid = (a[i].l + a[i].r)>>1; if(l > mid) query(l, r, i<<1|1, Max, Min); else if(r <= mid) query(l, r, i<<1, Max, Min); else{ int Max0, Max1, Min0, Min1; query(l, mid, i<<1, Max0, Min0); query(mid+1, r, i<<1|1, Max1, Min1); Max = max(Max0, Max1); Min = min(Min0, Min1); }}int main(){ int n, q, a, b, Max, Min; while(~scanf("%d%d", &n, &q)){ build(1, n, 1); for(int i = 0; i < q; i++){ scanf("%d%d", &a, &b); if(a == b){ puts("0"); continue; } query(a, b, 1, Max, Min); printf("%d\n", Max-Min); } } return 0;}

转载地址:https://blog.csdn.net/zhj_fly/article/details/76555192 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:RMQ算法
下一篇:线段树模板

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月15日 10时21分19秒