hihoCoder1586 Minimum 线段树

题目:

http://hihocoder.com/problemset/problem/1586?sid=1197111

题意:

给定一个序列,有两种操作:

  • 1 l r :从区间 [l,r] 内选出数字 ai , aj ,是的 aiaj 的值最小
  • 2 x y :把第 x 个元素的值更新为y

思路:

求区间内乘积的最小值,无非以下情况:都是正数时,直接取最小值相乘即可,有正数有负数的时候,取最小值和最大值相乘,都是负数时,取最大值相乘。维护最大值最小值用线段树即可

#include 

using namespace std;

const int N = 1000000 + 10, INF = 0x3f3f3f3f;

struct node
{
    int l, r, maxx, minn;
}tr[N*4];
int a[N];
void push_up(int k)
{
    tr[k].maxx = max(tr[k<<1].maxx, tr[k<<1|1].maxx);
    tr[k].minn = min(tr[k<<1].minn, tr[k<<1|1].minn);
}
void build(int l, int r, int k)
{
    tr[k].l = l, tr[k].r = r;
    if(l == r)
    {
        tr[k].maxx = tr[k].minn = a[l];
        return;
    }
    int mid = (l + r) >> 1;
    build(l, mid, k<<1);
    build(mid+1, r, k<<1|1);
    push_up(k);
}
void update(int x, int val, int k)
{
    if(tr[k].l == tr[k].r && x == tr[k].l)
    {
        tr[k].maxx = tr[k].minn = val; return;
    }
    int mid = (tr[k].l + tr[k].r) >> 1;
    if(x <= mid) update(x, val, k<<1);
    else update(x, val, k<<1|1);
    push_up(k);
}
int query(int l, int r, int f, int k)
{
    if(l <= tr[k].l && tr[k].r <= r)
    {
        return f ? tr[k].maxx : tr[k].minn;
    }
    int mid = (tr[k].l + tr[k].r) >> 1;
    int ans = f ? -INF : INF;
    if(l <= mid)
    {
        int t = query(l, r, f, k<<1);
        ans = f ? max(ans, t) : min(ans, t);
    }
    if(r > mid)
    {
        int t = query(l, r, f, k<<1|1);
        ans = f ? max(ans, t) : min(ans, t);
    }
    return ans;
}
int main()
{
    int t, n, m;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        n = 1 << n;
        for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
        build(1, n, 1);
        scanf("%d", &m);
        int opt, x, y;
        for(int i = 1; i <= m; i++)
        {
            scanf("%d%d%d", &opt, &x, &y);
            if(opt == 1)
            {
                ++x, ++y;
                int maxx = query(x, y, 1, 1), minn = query(x, y, 0, 1);
                printf("%lld\n", min(1LL*minn*minn, min(1LL*minn*maxx, 1LL*maxx*maxx)));
            }
            else
            {
                ++x;
                update(x, y, 1);
            }
        }
    }
    return 0;
}

你可能感兴趣的:(线段树)