Cod sursa(job #2855828)

Utilizator megulolMegu Lol megulol Data 22 februarie 2022 22:54:26
Problema Arbori de intervale Scor 50
Compilator rs Status done
Runda Arhiva educationala Marime 2.67 kb
use std::io::Read;
use std::io::BufReader;
use std::io::Write;

fn maxim(a: usize, b: usize) -> usize {
    if a > b {a} else {b}
}

fn update(arb: &mut [usize], node: usize, left: usize, right: usize, pos: usize, val: usize) {
    if left == right { arb[node] = val; return; }
    let mid = left + (right - left) / 2;
    if pos <= mid {
        update(arb, 2 * node, left, mid, pos, val);
    } else {
        update(arb, 2 * node + 1, mid + 1, right, pos, val);
    }
    arb[node] = maxim(arb[2 * node], arb[2 * node + 1]);
}

fn query(arb: &[usize], node: usize, left: usize, right: usize, start: usize, finish: usize, max: &mut usize) {
    if start <= left && right <= finish {
        if *max < arb[node] {
            *max = arb[node];
        }
        return;
    }
    let mid = left + (right - left) / 2;
    if start <= mid {
        query(arb, 2 * node, left, mid, start, finish, max);
    }
    if mid < finish {
        query(arb, 2 * node + 1, mid + 1, right, start, finish, max);
    }
}

fn main() {
    let mut file = BufReader::new(std::fs::File::open("arbint.in").unwrap());
    let mut input = String::new();
    file.read_to_string(&mut input).unwrap();
    let mut lines = input.lines();
    let (n, m) = lines.next().unwrap().trim().split_once(' ').unwrap();
    let n = n.parse::<usize>().unwrap();
    let m = m.parse::<usize>().unwrap();
    let mut arb = vec![0; 4 * n + 66];
    let mut i = 1;
    let mut j = 0;
    let bytes = lines.next().unwrap().as_bytes();
    while i <= n {
        let mut num = 0usize;
        while j < bytes.len() && !bytes[j].is_ascii_whitespace() {
            num = 10 * num + (bytes[j] - b'0') as usize;
            j += 1;
        }
        update(&mut arb, 1, 1, n, i, num);
        j += 1;
        i += 1;
    }
    let mut out = std::fs::File::create("arbint.out").unwrap();
    for _i in 0..m {
        let mut bytes = lines.next().unwrap().as_bytes();
        let mut j = 0;
        let mut x = 0;
        let mut a = 0;
        let mut b = 0;
        while j < bytes.len() && !bytes[j].is_ascii_whitespace() {
            x = 10 * x + (bytes[j] - b'0') as usize;
            j += 1;
        }
        j += 1;
        while j < bytes.len() && !bytes[j].is_ascii_whitespace() {
            a = 10 * a + (bytes[j] - b'0') as usize;
            j += 1;
        }
        j += 1;
        while j < bytes.len() && !bytes[j].is_ascii_whitespace() {
            b = 10 * b + (bytes[j] - b'0') as usize;
            j += 1;
        }
        j += 1;
        if x == 0 {
            let mut max = 0;
            query(&arb, 1, 1, n, a, b, &mut max);
            writeln!(out, "{}", max).unwrap();
        } else {
            update(&mut arb, 1, 1, n, a, b);
        }
    }
}