标签:
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
初看此题,可能会想到用最简单的暴力。可是结局很明显会被TLE。其实它是典型的线段树的例子,在完全二叉树中,总结点数不会超过叶子节点的两倍。
请看代码如下
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int const N=50010;
int a[N];
struct node
{
int l,r;
int low,high;
};
node tree[3*N];
int hei,low;
void build(int l,int r,int p)
{
tree[p].l=l;
tree[p].r=r;
if(l==r)
{
tree[p].low=a[l];
tree[p].high=a[l];
return;
}
int mid=(l+r)/2;
build(l,mid,2*p);
build(mid+1,r,2*p+1);
tree[p].low=min(tree[2*p].low,tree[2*p+1].low);
tree[p].high=max(tree[2*p].high,tree[2*p+1].high);
}
void ask(int l,int r,int p)
{
if(tree[p].l==l&&tree[p].r==r)
{
low=min(low,tree[p].low);
hei=max(hei,tree[p].high);
return ;
}
int mid=(tree[p].l+tree[p].r)/2;
if(r<=mid) ask(l,r,2*p);
else if(l>=mid+1) ask(l,r,2*p+1);
else
{
ask(l,mid,2*p);
ask(mid+1,r,2*p+1);
}
}
int main()
{
int m,n;
while(~scanf("%d%d",&m,&n))
{
for(int i=1;i<=m;i++)
scanf("%d",&a[i]);
build(1,m,1);
for(int i=1;i<=n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
low=1000001;
hei=0;
ask(x,y,1);
printf("%d\n",hei-low);
}
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/Amidgece/p/5721070.html