题目
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.
大概中文意思
给出N头奶牛的高度,求给定区间内的最大值和最小值
解法
直接暴力查找肯定会超时,和TSOJ的面朝大海春暖花开有点像?当时可以用差分、树状数组和线段树,但这里差分不知道会不会超时,消耗的空间也比较大,树状数组是求和的估计用不了(可能我太菜不知道其他用法)……行了我编不下去了作业要求就是线段树。
用线段树
线段树
第一次见到线段树也是面朝大海春暖花开那题,原理不再重复说了一搜一大把。
代码
只需要建树和查找,不用维护之类的……简单的模板题
我来写代码了,Ctrl+C,Ctrl+V
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define N 50001
int v[N], Max, Min;
struct node
{
int left, right;
int max, min;
int mid()
{
return (left + right) / 2;
}
} T[N * 3];
void build(int root, int l, int r) //建树
{
T[root].left = l;
T[root].right = r;
if (l == r)
{
T[root].max = T[root].min = v[l];
return ;
}
else
{
int mid = T[root].mid();
build(root << 1, l, mid);
build(root << 1 | 1, mid + 1, r);
T[root].max = max(T[root * 2].max, T[root * 2 + 1].max);
T[root].min = min(T[root * 2].min, T[root * 2 + 1].min);
}
}
void query(int root, int l, int r)
{
if (T[root].left == l && T[root].right == r)
{
Max = max(T[root].max, Max);
Min = min(T[root].min, Min);
return ;
}
else
{
int mid = T[root].mid();
if (r <= mid)
{
query(root << 1, l, r);
}
else if (l > mid)
{
query(root << 1 | 1, l, r);
}
else //拆两半
{
query(root << 1, l, mid);
query(root << 1 | 1, mid + 1, r);
}
}
}
int main()
{
int i, j, n, m;
cin>>n>>m;
for (i = 1; i <= n; i++)
cin>>v[i];
build(1, 1, n);
for (i = 1; i <= m; i++)
{
int st, en;
sin>>st>>en;
Max = -1000111222;
Min = 1000111222;
query(1, st, en);
cout<<Max-Min<<endl;
}
return 0;
}