博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Balanced Lineup
阅读量:5054 次
发布时间:2019-06-12

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

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

Source

1 #include 
2 #include
3 #define inf 1000000005 4 #include
5 using namespace std; 6 7 int a[50005]; 8 int mmin,mmax; 9 10 struct Node11 {12 int l,r;13 int min,max;14 }node[200100];15 16 void build(int root,int l,int r)17 {18 node[root].l = l;19 node[root].r = r;20 if(node[root].l==node[root].r)21 {22 node[root].min=a[l];23 node[root].max=a[l];24 return ;25 }26 int mid = (l+r)/2;27 build(root<<1,l,mid);28 build(root<<1|1,mid+1,r);29 node[root].min = min(node[root<<1].min,node[root<<1|1].min);30 node[root].max = max(node[root<<1].max,node[root<<1|1].max);31 }32 void query(int root,int l,int r)33 {34 if(l<=node[root].l && r>=node[root].r)35 {36 mmin = min(mmin,node[root].min);37 mmax = max(mmax,node[root].max);38 return;39 }40 int mid=(node[root].l+node[root].r)/2;41 42 if(r<=mid) query(root<<1,l,r);43 else if(l>=mid+1) query(root<<1|1,l,r);44 else45 {46 query(root<<1,l,mid);47 query(root<<1|1,mid+1,r);48 }49 }50 51 int main()52 {53 int n,q,b,c;54 while(scanf("%d %d",&n,&q)!=EOF)55 {56 for(int i=1; i<=n; i++) scanf("%d",&a[i]);57 build(1,1,n);58 while(q--)59 {60 scanf("%d%d",&b,&c);61 mmin = inf;62 mmax =-inf;63 query(1,b,c);64 printf("%d\n",mmax-mmin);65 }66 }67 68 return 0;69 }
线段树(单点更新)

 

转载于:https://www.cnblogs.com/contestant/p/3214608.html

你可能感兴趣的文章
跨平台开发 -- C# 使用 C/C++ 生成的动态链接库
查看>>
C# BS消息推送 SignalR介绍(一)
查看>>
WPF星空效果
查看>>
WPF Layout 系统概述——Arrange
查看>>
PIGOSS
查看>>
几款Http小服务器
查看>>
iOS 数组排序
查看>>
第三节
查看>>
PHP结合MYSQL记录结果分页呈现(比较实用)
查看>>
Mysql支持的数据类型
查看>>
openSuse beginner
查看>>
Codeforces 620E(线段树+dfs序+状态压缩)
查看>>
Windows7中双击py文件运行程序
查看>>
Market entry case
查看>>
bzoj1230 开关灯 线段树
查看>>
LinearLayout
查看>>
学习python:day1
查看>>
css3动画属性
查看>>
第九次团队作业-测试报告与用户使用手册
查看>>
Equal Sides Of An Array
查看>>