Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 62682 Accepted: 29231 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.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 2Sample Output
6 3 0
题意:
给定n头牛的身高,问某个区间内最高的牛和最矮的牛的身高差
思路:
线段树维护每段区间最高和最矮的牛的身高,区间查询最高和最矮做差
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <cmath>
#include <vector>
#include <bitset>
#define max_ 200010
#define inf 0x3f3f3f3f
#define ll long long
#define les 1e-8
#define mod 364875103
using namespace std;
struct node
{
int l,r;
int w;
int maxx;
int minn;
};
struct node tree[max_*4];
int n,m;
void built(int i,int l,int r)
{
tree[i].l=l;
tree[i].r=r;
if(l==r)
{
scanf("%d",&tree[i].w);
tree[i].maxx=tree[i].minn=tree[i].w;
return;
}
int mid=(l+r)>>1;
built(i<<1,l,mid);
built(i<<1|1,mid+1,r);
tree[i].maxx=max(tree[i<<1].maxx,tree[i<<1|1].maxx);
tree[i].minn=min(tree[i<<1].minn,tree[i<<1|1].minn);
}
int querymaxx(int i,int l,int r)
{
if(tree[i].l==l&&tree[i].r==r)
{
return tree[i].maxx;
}
int mid=(tree[i].l+tree[i].r)>>1;
if(r<=mid)
return querymaxx(i<<1,l,r);
else if(l>mid)
return querymaxx(i<<1|1,l,r);
else
return max(querymaxx(i<<1,l,mid),querymaxx(i<<1|1,mid+1,r));
}
int queryminn(int i,int l,int r)
{
if(tree[i].l==l&&tree[i].r==r)
{
return tree[i].minn;
}
int mid=(tree[i].l+tree[i].r)>>1;
if(r<=mid)
return queryminn(i<<1,l,r);
else if(l>mid)
return queryminn(i<<1|1,l,r);
else
return min(queryminn(i<<1,l,mid),queryminn(i<<1|1,mid+1,r));
}
int main(int argc, char const *argv[]) {
while(scanf("%d%d",&n,&m)!=EOF)
{
built(1,1,n);
while(m--)
{
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",querymaxx(1,l,r)-queryminn(1,l,r));
}
}
return 0;
}