码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3264 线段树+二分

时间:2016-07-30 16:45:42      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

 

初看此题,可能会想到用最简单的暴力。可是结局很明显会被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;
}

POJ 3264 线段树+二分

标签:

原文地址:http://www.cnblogs.com/Amidgece/p/5721070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!