Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 56391 | Accepted: 26423 | |
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
Lines 2..N+1: Line i+1 contains a single integer that is the height of cowi
Lines N+2..N+Q+1: Two integers A and B (1 ≤A ≤B ≤ N), representing the range of cows from A toB inclusive.
Output
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
题意描述:农夫约翰有N头奶牛,每头牛都有差异,现在农夫约翰想进行查询一定范围内的奶牛的高度最大值和最小值的差,奶牛查询操作数量为(1 ≤N ≤ 50,000),查询次数为(1 ≤Q ≤ 200,000)。
解题思路:本题奶牛数目不是很多,但是查询次数非常多,如果使用常规方法遍历特定范围找出最大值以及最小值,则时间复杂度为(O(n)),那么本题会超时,因此,我们要找到更加优化的方法。
方法(一):利用线段树,根据线段树的性质,我们可以将其最大值和最小值保留下来,根据线段树的性质,所有的叶子节点即为相应奶牛高度,其父亲节点保存其子节点的最大值和最小值,依次重复,时间复杂度为(O(log(n))
AC code:
#include<stdio.h>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
int leak[1000005];
int tmax = 0;
int tmin = 123456789;
struct trees{
// u代表最大值,v代表最小值
int u;
int v;
}tree[3000005];
// 递归构造线段树 ,root根节点初始值为 0
// 指针传递数组,leak为输入元素数组
void build(int root,int first,int end,int *leak){
int mid = (first + end)/2;
//first == end 表明是递归终点,进行元素赋值
if(first == end)
{
tree[root].v = leak[first];
tree[root].u = leak[first];
}
else{
build(root*2+1,first,mid,leak);
build(root*2+2,mid+1,end,leak);
//子节点得到赋值,父亲节点也要更新
tree[root].v = min(tree[root*2+1].v , tree[root*2+2].v);
tree[root].u = max(tree[root*2+1].u , tree[root*2+2].u);
}
}
//元素查找
//x、y表示查找目标区间,treeleft、treeright表示树的递归查找区间
// treeleft 初始值为 0 treeright初始值为奶牛数目
void find(int root ,int x,int y,int treeleft,int treeright){
int mid = (treeleft + treeright)/2;
//查询区间不在区间内
if( x > treeright || y< treeleft ) {
return;
}
//查询区间大于树的当前递归区间,更新最大最小值
else if(x<=treeleft && y >= treeright)
{
tmin = min(tmin,tree[root].v) ;
tmax = max(tmax,tree[root].u) ;
return ;
}
//其他查询区间
else{
find(root*2+1,x,y,treeleft,mid);
find(root*2+2,x,y,mid+1,treeright);
}
}
int main(void){
int a,b;
int i,j;
scanf("%d%d",&a,&b);
for(i=0;i<a;i++)
scanf("%d",&leak[i]);
build(0,0,a-1,leak);
for(i=0;i<b;i++){
int x,y;
scanf("%d%d",&x,&y);
tmax = 0;
tmin = 123456789;
find(0,x-1,y-1,0,a-1);
printf("%d\n",tmax-tmin);
}
}