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
思路:
线段树基础题,求一个区间最大值和最小值的差值,所以我们只需要存下来每个区间的最大值和最小值,用两个变量max1和min1来保存当前区间的最大值和最小值,然后每次查询直接读出计算即可。
AC代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
#include<map>
#define INF 0x3f3f3f3f
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
#define fori(x) for(int i=0;i<x;i++)
#define forj(x) for(int j=0;j<x;j++)
#define memset(x,y) memset(x,y,sizeof(x))
#define memcpy(x,y) memcpy(x,y,sizeof(x))
//#include <bits/stdc++.h>
typedef long long ll;
const int maxn=1e6+7;
const int mod=1e9+7;
const double eps=1e-8;
using namespace std;
int ac[50010];
struct node{
int l,r,max1,min1;
}t[140000];
int max1,min1;
void build(int k,int l,int r){
t[k].l=l;
t[k].r=r;
if(l==r)
{
t[k].max1=ac[l];
t[k].min1=ac[l];
}
else{
int mm=(l+r)/2;
build(k*2,l,mm);//左孩子
build(k*2+1,mm+1,r);//右孩子
t[k].max1=max(t[k*2].max1,t[k*2+1].max1);
t[k].min1=min(t[k*2].min1,t[k*2+1].min1);
}
}
void query(int x,int y,int k)
{
if(x<=t[k].l && y>=t[k].r)
{
max1 = max(max1,t[k].max1);
min1 = min(min1,t[k].min1);
}
else{
int mm=(t[k].l+t[k].r)/2;
if(x>=mm+1) query(x,y,k*2+1);
else if(y<=mm) query(x,y,k*2);
else{
query(x,y,k*2);
query(x,y,k*2+1);
}
}
}
int main(){
int n,q;
scanf("%d%d",&n,&q);
rep(i,1,n+1)
{
scanf("%d",&ac[i]);
}
build(1,1,n);
while(q--)
{
max1 = -1;
min1 = INF;
int l,r;
scanf("%d%d",&l,&r);
query(l,r,1);
//printf("%d %d\n",max1,min1);
printf("%d\n",max1 - min1);
}
return 0;
}
本文介绍了一种使用线段树数据结构解决区间最大值和最小值问题的方法,通过构建线段树并存储每个区间的最大值和最小值,可以高效地查询任意指定区间内的高度差,适用于处理大量区间查询的情况。
3229

被折叠的 条评论
为什么被折叠?



