Cod sursa(job #3002555)

Utilizator brianna_enacheEnache Brianna brianna_enache Data 14 martie 2023 21:19:40
Problema Arbori de intervale Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>
using namespace std;

/**
n+n/2+n/4+...+n/2^k = n(1+1/2+1/4+...+1/2^k)

    1 - 1/2^(k+1)     2^(k+1) - 1           2n-1
n * ------------ = 2n*--------------- = 2n*--------=2n-1
     1-1/2                2^(k+1)            2n


    1 2 3 4 5 6 7  8 9 10 11 12 13 14 15
a = 2,5,2,5,7,2,3,14,5, 7, 9,12, 2,17, 3
    10  10    10                10

a[i] = min(a[2*i, a[2*i+1])

a[n+0], a[n+1], ..., a[n+n-1]

n=18 => n=32 => 2n-1=63

n=8
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
a =               1 6  4  3  9 oo oo oo
*/

ifstream in("arbint.in");
ofstream out("arbint.out");
int a[400005], n;

void Update(int p, int val)
{
    int k;
    a[p] = val;
    while (p > 1)
    {
        k = p / 2;
        a[k] = max(a[2 * k], a[2 * k + 1]);
        p = k;
    }
}

/// care este valoarea minima pe intervalul [x,y]?
int Query(int p, int x, int y, int st, int dr)
{
    if (x == st && y == dr) return a[p];
    int m = (st + dr) / 2;
    if (y <= m) /// [x,y] este inclus in [st,m]
        return Query(2 * p, x, y, st, m);
    if (m + 1 <= x) /// [x,y] este inclus in [m+1,dr]
        return Query(2 * p + 1, x, y, m + 1, dr);
    /// aici am x <= m < y
    return max(Query(2 * p, x, m, st, m),
           Query(2 * p + 1, m+1, y, m + 1, dr));
}

int main()
{
    int x, y, Q, op, i, k, oo = 2e9;
    in >> k >> Q;
    n = 1;
    while (n < k) n *= 2;
    for (i = n; i < n + k; i++)
        in >> a[i];
    for (i = n + k; i < 2 * n; i++)
        a[i] = oo;
    for (i = n - 1; i >= 1; i--)
        a[i] = max(a[2*i], a[2*i+1]);
    while (Q--)
    {
        in >> op >> x >> y;
        if (op == 0) out << Query(1, x, y, 1, n) << "\n";
        else Update(x + n - 1, y);
    }
    return 0;
}