POJ - 3264 - Balanced Lineup
先上题目
Balanced Lineup
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 28206 | Accepted: 13220 | |
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.
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
Source
今天训练吃蛋,好伤心,看得懂的两道题都超时了。这一题看得出是用线段树做可是当时不会撸线段树,现在还是不会= =。沉痛的打击。
题意很简单,就是给一系列的数,然后给出很多组范围给你,求这些范围中的最大值和最少值的差。
用线段树撸就可以过。
现在线段树还是不太会,而且最近精神不是很好,容易犯小错误,例如打错几个字什么的。这几天如果可以的话整理一下线段树的知识,毕竟这种结构很使用。
上代码:
1 #include <stdio.h> 2 #include <string.h> 3 #define MAX (50000+10) 4 #define Max(x,y) (x>y ? x : y) 5 #define Min(x,y) (x<y ? x : y) 6 #define INF 9999999 7 using namespace std; 8 9 int s[MAX],minn,maxn; 10 11 typedef struct 12 { 13 int l,r; 14 int maxh,minh; 15 }Node; 16 17 Node T[MAX<<2]; 18 19 void build(int l,int r,int p) 20 { 21 T[p].l=l; 22 T[p].r=r; 23 if(l==r) 24 { 25 T[p].maxh=T[p].minh=s[l]; 26 return ; 27 } 28 int mid=(l+r)>>1; 29 build(l,mid,p<<1); 30 build(mid+1,r,(p<<1)+1); 31 T[p].maxh=Max(T[p<<1].maxh,T[(p<<1)+1].maxh); 32 T[p].minh=Min(T[p<<1].minh,T[(p<<1)+1].minh); 33 } 34 35 void query(int l,int r,int p) 36 { 37 if(l<=T[p].l && r>=T[p].r) 38 { 39 minn=Min(minn,T[p].minh); 40 maxn=Max(maxn,T[p].maxh); 41 return ; 42 } 43 int mid=(T[p].l+T[p].r)>>1; 44 if(mid<l) query(l,r,(p<<1)+1); 45 else if(mid>=r) query(l,r,(p<<1)); 46 else 47 { 48 query(l,r,p<<1); 49 query(l,r,(p<<1)+1); 50 } 51 } 52 53 int main() 54 { 55 int i,n,q,l,r; 56 memset(s,0,sizeof(s)); 57 memset(T,0,sizeof(T)); 58 scanf("%d %d",&n,&q); 59 for(i=1;i<=n;i++) scanf("%d",&s[i]); 60 build(1,n,1); 61 for(i=1;i<=q;i++) 62 { 63 scanf("%d %d",&l,&r); 64 maxn=-INF; 65 minn=INF; 66 query(l,r,1); 67 printf("%d\n",maxn-minn); 68 } 69 return 0; 70 }