程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> poj3264 Balanced Lineup(求區間的最大值與最小值之差)

poj3264 Balanced Lineup(求區間的最大值與最小值之差)

編輯:關於C++

 

Balanced Lineup Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 37869   Accepted: 17751 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 ≤ ABN), 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

解題思路:先求最大值,再求最小值

 

/*******************************************************************************
 * Author :          jinbao
 * Email :           [email protected]
 * Last modified :   2015-05-11 20:30
 * Filename :        poj3264.cpp
 * Description :     
 * *****************************************************************************/
#include 
#include 
using namespace std;
#define min(x,y) xy?x:y
const int MAX = 50000+1;
struct cow{
	int Min,Max;
}p[4*MAX];
int a[MAX];
void build(int node,int begin,int end){
	if (begin==end){
		scanf("%d",&a[begin]);
		p[node].Min=p[node].Max=a[begin];
	}
	else{
		build(node*2,begin,(begin+end)/2);
		build(node*2+1,(begin+end)/2+1,end);
		p[node].Min=min(p[node*2].Min,p[node*2+1].Min);
		p[node].Max=max(p[node*2].Max,p[node*2+1].Max);
	}
}
int query(int node,int begin,int end,int left,int right,int flag){
	if (endright){
		if (flag==0)
			return 0xffffff;
		return -1;
	}
	if (begin>=left && end<=right){
		if (flag==0)
			return p[node].Min;
		return p[node].Max;
	}
	int m=query(2*node,begin,(begin+end)/2,left,right,flag);
	int n=query(2*node+1,(begin+end)/2+1,end,left,right,flag);
	if (flag==0)
		return min(m,n);
	return max(m,n);
}
int main(){
	int n,q,l,r,Min,Max;
	while (~scanf("%d%d",&n,&q)){
		build(1,1,n);
		while (q--){
			scanf("%d%d",&l,&r);
			int ans = query(1,1,n,l,r,1) - query(1,1,n,l,r,0);
			printf("%d\n",ans);
		}
	}

	return 0;
}


 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved