poj3264_Balanced Lineup
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj3264_Balanced Lineup相关的知识,希望对你有一定的参考价值。
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 42349 | Accepted: 19917 | |
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
线段树维护区间最大值、最小值,然后相减。AC代码:
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <map> 5 #include <string> 6 #include <string.h> 7 #include <queue> 8 #include <vector> 9 #include <set> 10 #include <cmath> 11 #define inf 0x7fffffff 12 using namespace std; 13 const int maxn=50000; 14 struct b{ 15 int imax,imin; 16 }tree[maxn*4+100]; 17 int n,q,x,y,a[maxn+100]; 18 void build(int p,int l,int r){ 19 if(l==r) {tree[p].imax=a[l],tree[p].imin=a[l];return ;} 20 int mid=(l+r)/2; 21 build(p*2,l,mid); 22 build(p*2+1,mid+1,r); 23 tree[p].imax=max(tree[p*2].imax,tree[p*2+1].imax); 24 tree[p].imin=min(tree[p*2].imin,tree[p*2+1].imin); 25 } 26 int findmin(int p,int l,int r,int x,int y){ 27 if(x<=l&&r<=y) return tree[p].imin; 28 int mid=(l+r)/2; 29 if(x>mid) return findmin(p*2+1,mid+1,r,x,y); 30 if(y<=mid) return findmin(p*2,l,mid,x,y); 31 return min(findmin(p*2+1,mid+1,r,x,y),findmin(p*2,l,mid,x,y)); 32 } 33 int findmax(int p,int l,int r,int x,int y){ 34 if(x<=l&&r<=y) return tree[p].imax; 35 int mid=(l+r)/2; 36 if(x>mid) return findmax(p*2+1,mid+1,r,x,y); 37 if(y<=mid) return findmax(p*2,l,mid,x,y); 38 return max(findmax(p*2+1,mid+1,r,x,y),findmax(p*2,l,mid,x,y)); 39 } 40 int main() 41 { 42 scanf("%d%d",&n,&q); 43 for(int i=1;i<=n;i++) 44 scanf("%d",&a[i]); 45 build(1,1,n); 46 for(int i=1;i<=q;i++){ 47 scanf("%d%d",&x,&y); 48 printf("%d\n",findmax(1,1,n,x,y)-findmin(1,1,n,x,y)); 49 } 50 return 0; 51 }
以上是关于poj3264_Balanced Lineup的主要内容,如果未能解决你的问题,请参考以下文章
poj3264 Balanced Lineup 2011-12-20