POJ 3264 Balanced Lineup

本文介绍了一种使用ST算法解决连续区间内最大值与最小值问题的方法,该方法适用于快速查询特定范围内最大高度与最小高度之差的问题,通过预先处理达到nlogn的时间复杂度,并能在O(1)时间内完成查询。

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.


【题目分析】
学习一下ST算法。nlogn的预处理和O(1)的查询。复杂度和线段树相同,常熟略小。


【代码】

#include <cstdio>
#include <cmath>
int mi[50001][17],mx[50001][17],a[50001],n,q,l,r;
inline int max(int a,int b){return a>b?a:b;}
inline int min(int a,int b){return a>b?b:a;}
inline void init()
{
    int m=(int)((log(n*1.0))/log(2.0));
    for (int i=1;i<=n;++i) mi[i][0]=mx[i][0]=a[i];
    for (int i=1;i<=m;++i)
        for (int j=1;j<=n;++j)
        {
            mi[j][i]=mi[j][i-1],mx[j][i]=mx[j][i-1];
            if(j+(1<<(i-1))<=n) mx[j][i]=max(mx[j][i],mx[j+(1<<(i-1))][i-1]);
            if(j+(1<<(i-1))<=n) mi[j][i]=min(mi[j][i],mi[j+(1<<(i-1))][i-1]);
        }
}
inline int ri(int l,int r)
{
    int m=(int)(log((r-l+1)*1.0)/log(2.0));
    return min(mi[l][m],mi[r-(1<<m)+1][m]);
}
inline int rx(int l,int r)
{
    int m=(int)(log((r-l+1)*1.0)/log(2.0));
    return max(mx[l][m],mx[r-(1<<m)+1][m]);
}
int main()
{
    scanf("%d%d",&n,&q);
    for (int i=1;i<=n;++i) scanf("%d",&a[i]);
    init();
    for (int i=1;i<=q;++i)
    {
        scanf("%d%d",&l,&r);
        printf("%d\n",rx(l,r)-ri(l,r));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值