题意:给出一组数,快速查询某个区间中的最大值和最小值。计算最大最小值的差
思路:线段树解决,时间为O(logn)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int MAXN=0x3f3f3f3f;
const int NUMB=200000;
typedef struct Node {
int val;
int left;
int right;
int minn;
int maxn;
int mid(){
return (left+right)/2;
}
}Node;
Node tree[2*NUMB+10];
int num[NUMB];
int p=0;
int all=0;
int ansMIN,ansMAX;
void create_tree(int x){
if(tree[x].left==tree[x].right) {tree[x].val=tree[x].minn=tree[x].maxn=num[++p];return;}
tree[2*x].left=tree[x].left;tree[2*x].right=tree[x].mid();
tree[2*x+1].left=tree[x].mid()+1;tree[2*x+1].right=tree[x].right;
create_tree(2*x);
create_tree(2*x+1);
tree[x].minn=min(tree[2*x].minn,tree[2*x+1].minn);tree[x].maxn=max(tree[2*x].maxn,tree[2*x+1].maxn);
return ;
}
void find_tree(int y,int st,int en){
if(tree[y].minn>=ansMIN&&tree[y].maxn<=ansMAX)
return ;
if(tree[y].left==st&&tree[y].right==en){
ansMAX=max(ansMAX,tree[y].maxn);
ansMIN=min(ansMIN,tree[y].minn);
return ;
}
if(tree[y].mid()>=en){
find_tree(y*2,st,en);
}else if(tree[y].mid()<st){
find_tree(y*2+1,st,en);
}else{
find_tree(y*2,st,tree[y].mid());
find_tree(y*2+1,tree[y].mid()+1,en);
}
return ;
}
int main()
{
int n,m,x,y;
while(~scanf("%d%d",&n,&m)){
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
for(int i=0;i<=2*n;i++){
tree[i].maxn=-MAXN;
tree[i].minn=MAXN;
tree[i].val=-1;
}
tree[1].left=1;tree[1].right=n;
create_tree(1);
//cal_tree();
while(m--){
scanf("%d%d",&x,&y);
ansMIN=MAXN;
ansMAX=-MAXN;
find_tree(1,x,y);
cout<<ansMAX-ansMIN<<endl;
}
}
}
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
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
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0