| Time Limit: 5000MS | Memory Limit: 65536K | |
| Total Submissions: 56516 | Accepted: 26478 | |
| 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
tips:线段树
#include<iostream> #include<cstring> #include<cstdio> using namespace std; const int maxn=55555; const int maxh=1111111; int MAX[maxn<<2]; int MIN[maxn<<2]; int n,q; void pushup(int rt) { MAX[rt]=max(MAX[rt<<1],MAX[rt<<1|1]); MIN[rt]=min(MIN[rt<<1],MIN[rt<<1|1]); } void build(int rt,int l,int r) { if(l==r){ scanf("%d",MAX+rt); MIN[rt]=MAX[rt]; return; } int m=(l+r)>>1; build(rt<<1,l,m); build(rt<<1|1,m+1,r); pushup(rt); } int query1(int rt,int l,int r,int ll,int rr) { if(ll<=l&&rr>=r){ return MAX[rt]; } int m=(l+r)>>1; int ret=0; if(ll<=m)ret=max(ret,query1(rt<<1,l,m,ll,rr)); if(rr>m)ret=max(ret,query1(rt<<1|1,m+1,r,ll,rr)); return ret; } int query2(int rt,int l,int r,int ll,int rr) { if(ll<=l&&rr>=r){ return MIN[rt]; } int m=(l+r)>>1; int ret=0x7fffffff; if(ll<=m)ret=min(ret,query2(rt<<1,l,m,ll,rr)); if(rr>m)ret=min(ret,query2(rt<<1|1,m+1,r,ll,rr)); return ret; } int main() { cin>>n>>q; build(1,1,n); while(q--) { int x,y;scanf("%d %d",&x,&y); printf("%d\n",query1(1,1,n,x,y)-query2(1,1,n,x,y)); } return 0; }
探讨了如何通过线段树算法确定参与游戏的奶牛组中最高与最矮个体的高度差,确保游戏的公平性。
1万+

被折叠的 条评论
为什么被折叠?



