POJ3264-Balanced Lineup

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

分析:

题意:N头牛,数列记录的是每头牛的身高,然后是Q行询问,查询a-b之间最高与最低身高的差值!

解析:
简单的线段树,不多做介绍!

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#define N 50005
#define INF 2000005

using namespace std;

struct node{
	int hst,sht;
};

node tree[N<<2];
int Max,Min;

void updata(int l,int r,int i,int x,int v)
{
	if(l==r)
	{
		tree[i].hst=v;
		tree[i].sht=v;
		return;
	}
	int mid=(l+r)>>1;
	if(x<=mid)
		updata(l,mid,i<<1,x,v);
	else
		updata(mid+1,r,i<<1|1,x,v);
	tree[i].hst=max(tree[i<<1].hst,tree[i<<1|1].hst);
	tree[i].sht=min(tree[i<<1].sht,tree[i<<1|1].sht);
}

void query(int l,int r,int i,int lt,int rt)
{
	if(lt<=l&&r<=rt)
	{
		Max=max(Max,tree[i].hst);
		Min=min(Min,tree[i].sht);
		return;
	}
	int mid=(l+r)>>1;
	if(lt<=mid)
		query(l,mid,i<<1,lt,rt);
	if(rt>mid)
		query(mid+1,r,i<<1|1,lt,rt);
}

int main()
{
	int n,m,high,a,b;
	while(~scanf("%d%d",&n,&m))
	{
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&high);
			updata(1,n,1,i,high);
		}
		for(int i=1;i<=m;i++)
		{
			Max=-INF;
			Min=INF;
			scanf("%d%d",&a,&b);
			query(1,n,1,a,b);
			printf("%d\n",Max-Min);
		}
	}
	return 0;
}
发布了46 篇原创文章 · 获赞 16 · 访问量 412

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105019826