码迷,mamicode.com
首页 > 其他好文 > 详细

poj 3264 Balanced Lineup RMQ线段树实现

时间:2015-02-02 23:19:29      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:rmq   acm   数据结构   线段树   balanced lineup   

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 36613   Accepted: 17141
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

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


这题RMQ问题,RMQ最好使用使用ST算法实现,效率可能比较高。。我用的线段树,用了1500ms。。。(掩面

可能是我写的渣吧,等有时间学一下st算法,毕竟用线段树能不能AC可能要看人品了。或许是我的代码写的太渣,还有可以优化的地方却没有优化。就这样吧。代码还是比较容易理解的


#include <stdio.h>
#include <limits.h>

#define MAX 501000
struct tree{
	int t,s;
}st[MAX*4];

int tall=INT_MIN,shor=INT_MAX ;
int max(int a ,int b)
{
	return a>b?a:b;
}

int min(int a ,int b)
{
	return a>b?b:a ;
}
void build(int left , int right , int pos)
{
	if(left == right)
	{
		scanf("%d",&st[pos].t);
		st[pos].s = st[pos].t;
		return ;
	}
	int mid = (left + right)>>1;
	build(left,mid,pos<<1);
	build(mid+1,right,pos<<1|1) ;
	st[pos].t = max(st[pos<<1].t,st[pos<<1|1].t) ;
	st[pos].s = min(st[pos<<1].s,st[pos<<1|1].s) ;
}
//L,R大区间, 
void query(int L,int R,int x, int y ,int pos)
{
	if(L == x && R == y)
	{
		tall = max(tall,st[pos].t);
		shor = min(shor,st[pos].s);
		return ;
	}
	int mid = (L+R)>>1;
	if(mid < x)
	{
		query(mid+1,R,x,y,pos<<1|1);
	}
	else if(mid >= y)
	{
		query(L,mid,x,y,pos<<1) ;
	}
	else
	{
		query(L,mid,x,mid,pos<<1);
		query(mid+1,R,mid+1,y,pos<<1|1) ;
	}
}
int main()
{
	int n,q;
	scanf("%d%d",&n,&q);
	build(1,n,1);
	for(int i = 0 ; i < q ; ++i)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		tall=INT_MIN,shor=INT_MAX ;
		query(1,n,a,b,1) ;
		printf("%d\n",tall-shor) ;
	}
	return 0 ;
}


poj 3264 Balanced Lineup RMQ线段树实现

标签:rmq   acm   数据结构   线段树   balanced lineup   

原文地址:http://blog.csdn.net/lionel_d/article/details/43412109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!