POJ-3264 Balanced Lineup
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 Ato 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<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int ma[220000],mi[220000];
void creat(int l,int r,int o)//建立树状树
{
if(l==r)
{
scanf("%d",&ma[o]);
mi[o]=ma[o];
return ;
}
int mid=(r+l)>>1;
creat(l,mid,o<<1);
creat(mid+1,r,o<<1|1);
ma[o]=max(ma[o<<1],ma[o<<1|1]);
mi[o]=min(mi[o<<1],mi[o<<1|1]);
}
int ask1(int x,int y,int l,int r,int o)//最大值
{
while(l>=x&&r<=y)
return ma[o];
int mid=(l+r)>>1;
int t1=0,t2=0;
if(x<=mid)
t1=ask1(x,y,l,mid,o<<1);
if(y>mid)
t2=ask1(x,y,mid+1,r,o<<1|1);
return max(t1,t2);
}
int ask2(int x,int y,int l,int r,int o)//最小值
{
while(l>=x&&r<=y)
return mi[o];
int mid=(l+r)>>1;
int t1=0x3f3f3f3f,t2=0x3f3f3f3f;
if(x<=mid)
t1=ask2(x,y,l,mid,o<<1);
if(y>mid)
t2=ask2(x,y,mid+1,r,o<<1|1);
return min(t1,t2);
}
int main()
{
int n,m;
while(~scanf("%d",&n))
{
scanf("%d",&m);
memset(ma,0,sizeof(ma));
memset(mi,0,sizeof(mi));
creat(1,n,1);
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
int t1=ask1(a,b,1,n,1);
int t2=ask2(a,b,1,n,1);
printf("%d\n",t1-t2);
}
}
return 0;
}
上一篇: 输入一批整数,使用循环求出最大值与最小值,输入0时结束
下一篇: Python之heapq模块
推荐阅读
-
POJ-3264 Balanced Lineup
-
E. K Balanced Teams
-
LuoguP3069 【[USACO13JAN]牛的阵容Cow Lineup
-
HDU6299 Balanced Sequence (多校第一场1002) (贪心)
-
G. Livestock Lineup
-
21天刷题计划之18.1—balanced-binary-tree(平衡二叉树)(Java语言描述)
-
C基础 - 终结 Size Balanced Tree
-
平衡二叉树(Balanced Binary Tree 或 Height-Balanced Tree)又称AVL树
-
Codeforces Round #668 (Div. 2)-C. Balanced Bitstring
-
E. K Balanced Teams