#[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; use std::io::Read; #[allow(dead_code)] fn getline() -> String { let mut ret = String::new(); std::io::stdin().read_line(&mut ret).ok().unwrap(); ret } fn get_word() -> String { let mut stdin = std::io::stdin(); let mut u8b: [u8; 1] = [0]; loop { let mut buf: Vec = Vec::with_capacity(16); loop { let res = stdin.read(&mut u8b); if res.unwrap_or(0) == 0 || u8b[0] <= b' ' { break; } else { buf.push(u8b[0]); } } if buf.len() >= 1 { let ret = String::from_utf8(buf).unwrap(); return ret; } } } #[allow(dead_code)] fn get() -> T { get_word().parse().ok().unwrap() } fn solve() { let n = get(); assert!(n <= 4000); let a: Vec = (0 .. n).map(|_| get()).collect(); // Precomputation // Counts how many kadomatsu seqs. with the center a[i] can be made. // TODO very slow, O(n^2) let mut aux: Vec = vec![0; n]; for i in 0 .. n { let mut cnt = 0; for j in 0 .. i { if a[j] == a[i] { continue; } for k in i + 1 .. n { if a[k] == a[i] { continue; } if a[j] != a[k] && ((a[j] < a[i] && a[i] > a[k]) || (a[j] > a[i] && a[i] < a[k])) { cnt += 1; } } } aux[i] = cnt; } const INF: i64 = 1 << 60; let mut acc = vec![(0, 0); n]; for i in 0 .. n { acc[i] = (a[i], aux[i]); } acc.push((-INF, 0)); acc.sort(); for i in 0 .. n + 1 { acc[i].1 += if i == 0 { 0 } else { acc[i - 1].1 }; } let q = get(); for _ in 0 .. q { let l: i64 = get(); let h: i64 = get(); let upper = acc.binary_search(&(h, INF)).unwrap_err(); let lower = acc.binary_search(&(l, -INF)).unwrap_err(); println!("{}", acc[upper - 1].1 - acc[lower - 1].1); } } fn main() { // In order to avoid potential stack overflow, spawn a new thread. let stack_size = 104_857_600; // 100 MB let thd = std::thread::Builder::new().stack_size(stack_size); thd.spawn(|| solve()).unwrap().join().unwrap(); }