POJ 3264 RMQ问题

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 ≤ ABN), 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 2

Sample Output

6
3
0

Source

    题目大意:有N头牛,对于第i头牛,它的高度是h[i];有Q个查询,每次查询给定一个区间[a,b],求第a头牛到第b头牛中最高的和最矮的相差多少。对于这种典型的RMQ问题,可以建立一棵线段树,然后查询。
#include <iostream>

#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
const int MAXN = 50001;

struct segment{
    
int left,right;
    
int high,low;
}
tree[MAXN*2];
int t,s,height[MAXN];

void create(int l,int r,int index){
    tree[index].left
=l,tree[index].right=r;
    
if(l==r){
        tree[index].high
=height[l];
        tree[index].low
=height[l];
        
return;
    }

    
int mid=(l+r)>>1;
    create(l,mid,
2*index);
    create(mid
+1,r,2*index+1);
    tree[index].high
=max(tree[2*index].high,tree[2*index+1].high);
    tree[index].low
=min(tree[2*index].low,tree[2*index+1].low);
}

void update(int l,int r,int index){
    
if(tree[index].left==&& tree[index].right==r){
        
if(tree[index].high>t) t=tree[index].high;
        
if(tree[index].low<s) s=tree[index].low;
        
return;
    }

    
int mid=(tree[index].left+tree[index].right)>>1;
    
if(r<=mid)
        update(l,r,
2*index);
    
else if(l>mid)
        update(l,r,
2*index+1);
    
else{
        update(l,mid,
2*index);
        update(mid
+1,r,2*index+1);
    }

}

int main(){
    
int i,n,q,x,y;
    scanf(
"%d %d",&n,&q);
    
for(i=1;i<=n;i++) scanf("%d",&height[i]);
    create(
1,n,1);
    
for(i=1;i<=q;i++){
        scanf(
"%d %d",&x,&y);
        t
=0,s=10000000;
        update(x,y,
1);
        printf(
"%d\n",t-s);
    }

    
return 0;
}

posted on 2009-05-14 16:05 极限定律 阅读(356) 评论(0)  编辑 收藏 引用 所属分类: ACM/ICPC


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2009年4月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

导航

统计

常用链接

留言簿(10)

随笔分类

随笔档案

友情链接

搜索

最新评论

阅读排行榜

评论排行榜