标签:
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
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
Source
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<map> #include<queue> #include<stack> #define INF 0xfffffff using namespace std; struct tree { int L; int R; int minv; int maxv; int mid() { return (L+R)/2; } }tree[800010]; int maxv=-INF; int minv=INF; void buildtree(int root,int L,int R) { tree[root].L=L; tree[root].R=R; tree[root].minv=INF; tree[root].maxv=-INF; if(L!=R) { buildtree(2*root+1,L,(L+R)/2); buildtree(2*root+2,(L+R)/2+1,R); } } void inse(int root,int i,int v) { if(tree[root].L==tree[root].R) { tree[root].minv=v; tree[root].maxv=v; return ; } tree[root].minv=min(tree[root].minv,v); tree[root].maxv=max(tree[root].maxv,v); if(i<=tree[root].mid()) inse(2*root+1,i,v); else inse(2*root+2,i,v); } void query(int root ,int s,int e) { if(tree[root].minv>minv&&tree[root].maxv<maxv) return ; if(tree[root].L==s&&tree[root].R==e) { minv=min(minv,tree[root].minv); maxv=max(maxv,tree[root].maxv); return ; } if(e<=tree[root].mid()) query(2*root+1,s,e); else if(s>tree[root].mid()) query(2*root+2,s,e); else { query(2*root+1,s,tree[root].mid()); query(2*root+2,tree[root].mid()+1,e); } } int main() { int n,q; int re; int ss,ee; scanf("%d%d",&n,&q); buildtree(0,1,n); for(int i=1; i<=n; i++) { //cout<<"**********"<<endl; scanf("%d",&re); inse(0,i,re); } for(int j=1; j<=q; j++) { scanf("%d%d",&ss,&ee); minv=INF; maxv=-INF; query(0,ss,ee); printf("%d\n",maxv-minv); } return 0; }
标签:
原文地址:http://www.cnblogs.com/hsd-/p/4671725.html