Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 32165 | Accepted: 15145 | |
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
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
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
思路:
题意主要是问在区间(x,y)中最大值与最小值的差是多少;
线段树差点问线,模版题;
参考 http://www.cnblogs.com/shuaiwhu/archive/2012/04/22/2464583.html
代码:
#include <stdio.h>
#define MY_MIN 99999999
#define MY_MAX -99999999
struct CNode{
int L, R;
int nMin, nMax;
CNode *pLeft, *pRight;
};
int min(const int a, const int b){
return (b < a) ? b : a;
}
int max(const int a, const int b){
return (b < a) ? a : b;
}
int nMax, nMin; // 用于记录最大值和最小值
CNode Tree[1000000]; // 一般为叶子节点的两倍
int nCount = 0; // 总节点数
void Build(CNode *pRoot, int L, int R){ // 建一个空的线段树
pRoot ->L = L;
pRoot ->R = R;
pRoot ->nMin = MY_MIN;
pRoot ->nMax = MY_MAX;
if(L != R){
nCount ++;
pRoot ->pLeft = Tree + nCount;
nCount ++;
pRoot ->pRight = Tree + nCount;
Build(pRoot ->pLeft, L, (L + R) / 2);
Build(pRoot ->pRight, (L + R) / 2 + 1, R);
}
}
void Insert(CNode *pRoot, int i, int v){ // i节点值为v
if(pRoot ->L == i && pRoot ->R == i){
pRoot ->nMin = pRoot ->nMax = v; // 叶子节点的Max值和Min值相等;
return;
}
pRoot ->nMax = max(pRoot ->nMax, v); // 跟新路过节点的Max和Min值
pRoot ->nMin = min(pRoot ->nMin, v);
if(i <= (pRoot ->R + pRoot ->L) / 2) // i节点在左子树
Insert(pRoot ->pLeft, i, v);
else // i节点在右子树
Insert(pRoot ->pRight, i, v);
}
void Query(CNode *pRoot, int L, int R){ // 询问
if(pRoot ->nMin >= nMin && pRoot ->nMax <= nMax)
return;
if(pRoot->L == L && pRoot->R == R){
nMax = max(pRoot ->nMax, nMax);
nMin = min(pRoot ->nMin, nMin);
return;
}
else if(R <= (pRoot ->R + pRoot ->L) / 2) // L在当前节点左端
Query(pRoot ->pLeft, L, R);
else if(L >= (pRoot ->R + pRoot ->L) / 2 + 1) // R在当前节点右端
Query(pRoot ->pRight, L, R);
else{ // 当前节点在L和R中间
Query(pRoot ->pLeft, L, (pRoot ->R + pRoot ->L) / 2);
Query(pRoot ->pRight, (pRoot ->R + pRoot ->L) / 2 + 1, R);
}
}
int main(){
int m, n, v, x, y;
scanf("%d %d", &m, &n); // m节点数,n询问数
Build(Tree, 1, m);
for(int i = 1; i <= m; i ++){
scanf("%d", &v);
Insert(Tree, i, v);
}
while(n --){
scanf("%d%d", &x, &y);
nMax = MY_MAX;
nMin = MY_MIN;
Query(Tree, x, y);
printf("%d\n", nMax - nMin);
}
return 0;
}