Problem: 2063B - Subsequence Update
Language: Rust 2021

Previous submission (verdict: Time limit exceeded on test 7):
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_macros)]
#![allow(unused_parens)]
#![allow(unused_variables)]
#![allow(static_mut_refs)]
#![allow(unused_mut)]

use std::cell::*;
use std::char;
use std::cmp::Ordering;
use std::cmp::Reverse;
use std::collections::*;
use std::io;
use std::io::sink;
use std::io::Read;
use std::io::StdinLock;
use std::io::Write;
use std::iter;
use std::mem;
use std::process::exit;
use std::str;

use std::collections::hash_map::Entry;

#[cfg(test)]
mod solution;

macro_rules! vwc {
    ($cap:expr) => {
        Vec::with_capacity($cap)
    };
}

macro_rules! bh {
    () => {
        BinaryHeap::new()
    };
    ($elem:expr; $n:expr) => {
        BinaryHeap::from(vec![elem; n])
    };
    ($($x:expr),+ $(,)?) => {
        BinaryHeap::from(vec![$($x),+])
    };
}

macro_rules! vd {
    () => {
        VecDeque::new()
    };
    ($elem:expr; $n:expr) => {
        VecDeque::from(vec![elem; n])
    };
    ($($x:expr),+ $(,)?) => {
        VecDeque::from(vec![$($x),+])
    };
}

macro_rules! hs {
    () => {
        HashSet::new()
    };
    ($($v:expr),+ $(,)?) => {
        HashSet::from([$($v),+])
    };
}

macro_rules! hm {
    () => {
        HashMap::new()
    };
    ($(($k:expr, $v:expr)),+ $(,)?) => {
        HashMap::from([$(($k, $v)),+])
    };
}

macro_rules! bts {
    () => {
        BTreeSet::new()
    };
    ($($v:expr),+ $(,)?) => {
        BTreeSet::from([$($v),+])
    };
}

macro_rules! btm {
    () => {
        BTreeMap::new()
    };
    ($(($k:expr, $v:expr)),+ $(,)?) => {
        BTreeMap::from([$(($k, $v)),+])
    };
}

#[derive(Debug)]
pub struct UnsafeScanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: str::SplitAsciiWhitespace<'static>,
    // '
}

impl<R: io::BufRead> UnsafeScanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buf_str: vec![],
            buf_iter: "".split_ascii_whitespace(),
        }
    }

    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader
                .read_until(b'\n', &mut self.buf_str)
                .expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_ascii_whitespace())
            }
        }
    }
}

macro_rules! cin {
    ($s:ident) => {
        $s.get_mut().expect("Should be initialized.").token()
    };
    ($s:ident, $t:ty) => {
        $s.get_mut().expect("Should be initialized.").token::<$t>()
    };
}

static mut scnr: OnceCell<UnsafeScanner<StdinLock<'static>>> = OnceCell::new();
//'

static mut MOD: u64 = 1_000_000_007;
static INF: i32 = i32::MAX - 1_000_000;
static NEGINF: i64 = i64::MIN + 1_000_000;

fn main() {
    let stdin = io::stdin();
    let s = UnsafeScanner::new(stdin.lock());
    unsafe {
        scnr.set(s).expect("Scanner shouldn't be initialized.");
    }

    let t: usize = unsafe { cin!(scnr) };

    for i in 0..t {
        unsafe {
            solve();
        }
    }
    exit(0);
}

#[inline(always)]
unsafe fn solve() {
    let n: usize = cin!(scnr);
    let l: usize = cin!(scnr, usize) - 1;
    let r: usize = cin!(scnr, usize) - 1;

    let mut minsum = vec![0_i64; (l + 1)];
    for i in 0..l {
        let v: i64 = cin!(scnr);
        for j in (0..=i).rev() {
            if minsum[j+1] == 0 || v + minsum[j] < minsum[j + 1] {
                minsum[j + 1] = v + minsum[j];
            }
        }
    }

    let mut sum = 0;
    let mut maxsum = vec![0; (r - l) + 2];
    for i in 0..(r - l + 1) {
        let v: i64 = cin!(scnr);
        sum += v;
        for j in (0..=i).rev() {
            if v + maxsum[j] > maxsum[j + 1] {
                maxsum[j + 1] = v + maxsum[j];
            }
        }
    }

    let mut minsum2 = vec![0_i64; (n - r)];
    for i in 0..(n - r - 1) {
        let v: i64 = cin!(scnr);
        for j in (0..=i).rev() {
            if minsum2[j+1] == 0 || v + minsum2[j] < minsum2[j + 1] {
                minsum2[j + 1] = v + minsum2[j];
            }
        }
    }

    //println!("minsum {:?}", minsum);
    //println!("maxsum {:?}", maxsum);
    //println!("minsum2 {:?}", minsum2);
    let mut rez = maxsum
        .iter()
        .zip(&minsum)
        .map(|(&max, &min)| max - min)
        .chain(maxsum.iter().zip(&minsum2).map(|(&max, &min)| max - min))
        .max()
        .unwrap();

    //println!("rez {}", rez);
    println!("{}", sum - rez.max(0));
}


Submission (verdict: Time limit exceeded on test 4):
#![allow(non_snake_case)]

#![allow(non_upper_case_globals)]

#![allow(unused_imports)]

#![allow(dead_code)]

#![allow(unused_macros)]

#![allow(unused_parens)]

#![allow(unused_variables)]

#![allow(static_mut_refs)]

#![allow(unused_mut)]



use std::cell::*;

use std::char;

use std::cmp::Ordering;

use std::cmp::Reverse;

use std::collections::*;

use std::io;

use std::io::sink;

use std::io::Read;

use std::io::StdinLock;

use std::io::Write;

use std::iter;

use std::mem;

use std::process::exit;

use std::str;



use std::collections::hash_map::Entry;



#[cfg(test)]

mod solution;



macro_rules! vwc {

    ($cap:expr) => {

        Vec::with_capacity($cap)

    };

}



macro_rules! bh {

    () => {

        BinaryHeap::new()

    };

    ($elem:expr; $n:expr) => {

        BinaryHeap::from(vec![elem; n])

    };

    ($($x:expr),+ $(,)?) => {

        BinaryHeap::from(vec![$($x),+])

    };

}



macro_rules! vd {

    () => {

        VecDeque::new()

    };

    ($elem:expr; $n:expr) => {

        VecDeque::from(vec![elem; n])

    };

    ($($x:expr),+ $(,)?) => {

        VecDeque::from(vec![$($x),+])

    };

}



macro_rules! hs {

    () => {

        HashSet::new()

    };

    ($($v:expr),+ $(,)?) => {

        HashSet::from([$($v),+])

    };

}



macro_rules! hm {

    () => {

        HashMap::new()

    };

    ($(($k:expr, $v:expr)),+ $(,)?) => {

        HashMap::from([$(($k, $v)),+])

    };

}



macro_rules! bts {

    () => {

        BTreeSet::new()

    };

    ($($v:expr),+ $(,)?) => {

        BTreeSet::from([$($v),+])

    };

}



macro_rules! btm {

    () => {

        BTreeMap::new()

    };

    ($(($k:expr, $v:expr)),+ $(,)?) => {

        BTreeMap::from([$(($k, $v)),+])

    };

}



#[derive(Debug)]

pub struct UnsafeScanner<R> {

    reader: R,

    buf_str: Vec<u8>,

    buf_iter: str::SplitAsciiWhitespace<'static>,

    // '

}



impl<R: io::BufRead> UnsafeScanner<R> {

    pub fn new(reader: R) -> Self {

        Self {

            reader,

            buf_str: vec![],

            buf_iter: "".split_ascii_whitespace(),

        }

    }



    pub fn token<T: str::FromStr>(&mut self) -> T {

        loop {

            if let Some(token) = self.buf_iter.next() {

                return token.parse().ok().expect("Failed parse");

            }

            self.buf_str.clear();

            self.reader

                .read_until(b'\n', &mut self.buf_str)

                .expect("Failed read");

            self.buf_iter = unsafe {

                let slice = str::from_utf8_unchecked(&self.buf_str);

                std::mem::transmute(slice.split_ascii_whitespace())

            }

        }

    }

}



macro_rules! cin {

    ($s:ident) => {

        $s.get_mut().expect("Should be initialized.").token()

    };

    ($s:ident, $t:ty) => {

        $s.get_mut().expect("Should be initialized.").token::<$t>()

    };

}



static mut scnr: OnceCell<UnsafeScanner<StdinLock<'static>>> = OnceCell::new();

//'



static mut MOD: u64 = 1_000_000_007;

static INF: i32 = i32::MAX - 1_000_000;

static NEGINF: i64 = i64::MIN + 1_000_000;



fn main() {

    let stdin = io::stdin();

    let s = UnsafeScanner::new(stdin.lock());

    unsafe {

        scnr.set(s).expect("Scanner shouldn't be initialized.");

    }



    let t: usize = unsafe { cin!(scnr) };



    for i in 0..t {

        unsafe {

            solve();

        }

    }

    exit(0);

}



#[inline(always)]

unsafe fn solve() {

    let n: usize = cin!(scnr);

    let l: usize = cin!(scnr, usize) - 1;

    let r: usize = cin!(scnr, usize) - 1;



    let mut A = vwc!(n);

    for i in 0..n {

        A.push( cin!(scnr) );

    }

    let mut sum: i64 = A[l..=r].iter().copied().sum();

    let rez = best_swap(&A[..l], &A[l..=r], &mut vec![vec![-1; n+1]; n+1]).max(best_swap(&A[r+1..], &A[l..=r], &mut vec![vec![-1; n+1]; n+1]));

    println!("{}", sum - rez.max(0));

}



fn best_swap(a: &[i64], b: &[i64], dp: &mut [Vec<i64>]) -> i64 {

    if a.is_empty() || b.is_empty() {

        return 0;

    }

    if dp[a.len()][b.len()] == -1 {

        dp[a.len()][b.len()] = best_swap(&a[1..], b, dp)

            .max(best_swap(a, &b[1..], dp))

            .max(b[0] - a[0] + best_swap(&a[1..], &b[1..], dp));

    }

    return dp[a.len()][b.len()];

}