(区间最值查询,st表/线段树/树状数组)Balanced Lineup

POJ - 3264
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.

n头牛,给出每头牛的高度,q次询问,求每次l到r区间的最高牛与最低牛的高度差
做法很多,简单题目

st表写法:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;

const int maxn = 50000 + 4;
int st[maxn][20][3];
void Build(int n) {
    for(int j = 1; j < 20; ++j) {
        for(int i = 1; i + (1 << (j - 1)) <= n; ++i) {
            st[i][j][0] = min(st[i][j - 1][0], st[i + (1 << (j - 1))][j - 1][0]);
            st[i][j][1] = max(st[i][j - 1][1], st[i + (1 << (j - 1))][j - 1][1]);
        }
    }
}
int Query(int l, int r) {
    int len = int(log((double)(r - l + 1)) / log(2.0));
    int minn = min(st[l][len][0], st[r - (1 << len) + 1][len][0]);
    int maxx = max(st[l][len][1], st[r - (1 << len) + 1][len][1]);
    return maxx - minn;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, q;
    cin >> n >> q;
    for(int i = 1; i <= n; ++i) {
        cin >> st[i][0][0];
        st[i][0][1] = st[i][0][0];
    }
    Build(n);
    while(q--) {
        int l, r;
        cin >> l >> r;
        if(l == r) cout << 0 << endl;
        else cout << Query(l, r) << endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值