A - Balanced Lineup
https://vjudge.net/contest/360158#problem
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
线段树的模板题,只需要建树插入查找即可
当然。。第一次写线段树这个变量取的比较繁琐。。。方便修改就是了(笑)
。。不过真的是看的头疼。。
#include <stdio.h>
#include <algorithm>
using namespace std;
#define MAXN 50000
int ansmin,ansmax;
struct node
{
int lc;//维护的左区域
int rc;//维护的右区域
int minn;
int maxn;
};
node tree[MAXN*4];
void build(int left_range,int right_range,int tree_root)
{
int mid=(left_range+right_range)/2;
tree[tree_root].lc=left_range;
tree[tree_root].rc=right_range;
tree[tree_root].maxn=-1;
tree[tree_root].minn=0x3f3f3f3f;
if(left_range==right_range)
return;//叶子节点直接跳出
build(left_range,mid,tree_root*2);
build(mid+1,right_range,tree_root*2+1);
}
void insert(int num,int tall,int tree_root)
{
if(num<tree[tree_root].lc||num>tree[tree_root].rc)
return;//不在节点维护的区域
int mid=(tree[tree_root].lc+tree[tree_root].rc)/2;
if(tree[tree_root].maxn<tall)
tree[tree_root].maxn=tall;//维护一下节点
if(tree[tree_root].minn>tall)
tree[tree_root].minn=tall;
if(tree[tree_root].lc==tree[tree_root].rc)
return;//是叶子节点
if(num<=mid)
insert(num,tall,tree_root*2);
else
insert(num,tall,tree_root*2+1);
}
void search(int s_left,int s_right,int tree_root)
{
int mid=(tree[tree_root].lc+tree[tree_root].rc)/2;
if(tree[tree_root].maxn<=ansmax||tree[tree_root].minn>=ansmin)
return;
if(tree[tree_root].lc==s_left&&tree[tree_root].rc==s_right)
{
ansmax=max(ansmax,tree[tree_root].maxn);
ansmin=min(ansmin,tree[tree_root].minn);
}
if(s_left>mid)
search(mid+1,s_right,tree_root*2+1);
else if(s_right<=mid)
search(s_left,mid,tree_root*2);
else
{
search(s_left,mid,tree_root*2);
search(mid+1,s_right,tree_root*2+1);
}
}
int main(void)
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
build(1,n,1);
for(int i=1;i<=n;i++)
{
int temp;
scanf("%d",&temp);
insert(i,temp,1);
}
while(m--)
{
ansmax=-1;
ansmin=0x3f3f3f3f;
int l,r;
scanf("%d%d",&l,&r);
search(l,r,1);
printf("%d\n",ansmax-ansmin);
}
}
}