RMQ问题

范围最小值问题,给出一个n个元素的数组, a1, a2,...,an, 查询, 计算 min{al, al+1, ...,ar}  书上是用树状数组做的, 然而我并没看懂, 有空就会看一看, 迟早会看懂的

#include<iostream>
using namespace std;
const int INF = 65535;
struct mtree
{
    int l, r, v, mmin;
}tree[100000];


void build(int node, int b, int e)
{
    tree[node].l = b;
    tree[node].r = e;
    tree[node].v  = 0;
    tree[node].mmin = INF;
    if(b == e)
        return;
    int mid = (b+e)>>1;
    if(b <= mid)
        build(node<<1, b, mid);
    if(e > mid)
        build(node<<1|1, mid+1, e);
}
void update(int node, int b, int e, int add)
{
    if(tree[node].l>=b && tree[node].r <=e)
    {
        tree[node].v = add;
        tree[node].mmin = add;
        return;
    }
    int mid = (tree[node].l + tree[node].r)>>1;
    if(b<=mid)
        update(node<<1, b, e, add);
    if(e>mid)
        update(node<<1|1, b, e, add);
    tree[node].mmin = min(tree[node<<1].mmin, tree[node<<1|1].mmin);
}
int query(int node, int b, int e)
{
    int ans1 = INF, ans2 = INF;
    if(tree[node].l >=b && tree[node].r <=e)
        return tree[node].mmin;
    int mid = (tree[node].l+tree[node].r)>>1;
    if(b<=mid)
        ans1 = query(node<<1, b, e);
    if(e>mid)
        ans2 = query(node<<1|1, b, e);
    return min(ans1, ans2);


}
int main()
{
    int T;
    cin >> T;
    int n;
    while(T--)
    {
        cin >> n;
        build(1, 1, n);
        for(int i=1; i<=n; i++)
        {
            int k;
            cin >> k;
            update(1,i, i, k);
        }
        char c;
        int l, r;
        while(cin >> c)
        {
            cin >> l >> r;
            if(c == 'Q')
                cout << query(1,l,r) << endl;
            else
                update(1,l,l,r);
        }


    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值