| Time Limit: 5000MS | Memory Limit: 65536K | |
| Total Submissions: 16163 | Accepted: 7468 | |
| 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
Source
题意很简单,就不翻译了。
此题数据量非常大,简单的模拟必然会超时,线段树是个不错的选择
我们可以通过线段树分别查找区间最大值和区间最小值,之差就是答案了。。
Source Code
| Problem: 3264 | User: bingshen | |
| Memory: 2384K | Time: 1954MS | |
| Language: C++ | Result: Accepted |
- Source Code
#include<stdio.h> #include<string.h> struct node { int max; int min; int l; int r; }; node tree[200000]; int h[50005]; int max,min; int MAX(int a,int b) { if(a>b) return a; else return b; } int MIN(int a,int b) { if(a>b) return b; else return a; } void build(int l,int r,int root) { tree[root].l=l; tree[root].r=r; if(l==r) { tree[root].max=h[l]; tree[root].min=h[l]; return; } int mid=(l+r)>>1; build(l,mid,root*2); build(mid+1,r,root*2+1); tree[root].max=MAX(tree[2*root].max,tree[2*root+1].max); tree[root].min=MIN(tree[2*root].min,tree[2*root+1].min); } void findmax(int l,int r,int root) { if(tree[root].l==l&&tree[root].r==r) { if(tree[root].max>max) max=tree[root].max; return; } int mid=(tree[root].l+tree[root].r)>>1; if(mid>=r) findmax(l,r,root*2); else if(mid<l) findmax(l,r,root*2+1); else { findmax(l,mid,root*2); findmax(mid+1,r,root*2+1); } } void findmin(int l,int r,int root) { if(tree[root].l==l&&tree[root].r==r) { if(tree[root].min<min) min=tree[root].min; return; } int mid=(tree[root].l+tree[root].r)>>1; if(mid>=r) findmin(l,r,root*2); else if(mid<l) findmin(l,r,root*2+1); else { findmin(l,mid,root*2); findmin(mid+1,r,root*2+1); } } int main() { int n,q,i,a,b; scanf("%d%d",&n,&q); for(i=1;i<=n;i++) scanf("%d",&h[i]); build(1,n,1); while(q--) { max=0; min=99999999; scanf("%d%d",&a,&b); findmax(a,b,1); findmin(a,b,1); printf("%d/n",max-min); } return 0; } -
果断的1Y,很久没这个感觉了。。
平衡阵容游戏问题
本文介绍了一个关于从连续的奶牛队伍中挑选合适高度范围内的成员进行游戏的问题,并使用线段树来高效地找出指定范围内最大值与最小值的差值。
1万+

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



