Problem:
Score : 1000 points

Problem Statement

You are given a sequence a = \{a_1, ..., a_N\} with all zeros, and a sequence b = \{b_1, ..., b_N\} consisting of 0 and 1. The length of both is N.

You can perform Q kinds of operations. The i-th operation is as follows:

Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1.

Minimize the hamming distance between a and b, that is, the number of i such that a_i \neq b_i, by performing some of the Q operations.

Constraints

1 \leq N \leq 200,000

b consists of 0 and 1.

1 \leq Q \leq 200,000

1 \leq l_i \leq r_i \leq N

If i \neq j, either l_i \neq l_j or r_i \neq r_j.

Input

Input is given from Standard Input in the following format:

N
b_1 b_2 ... b_N
Q
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

Print the minimum possible hamming distance.

Sample Input 1

3
1 0 1
1
1 3

Sample Output 1

1

If you choose to perform the operation, a will become \{1, 1, 1\}, for a hamming distance of 1.

Sample Input 2

3
1 0 1
2
1 1
3 3

Sample Output 2

0

If both operations are performed, a will become \{1, 0, 1\}, for a hamming distance of 0.

Sample Input 3

3
1 0 1
2
1 1
2 3

Sample Output 3

1

Sample Input 4

5
0 1 0 1 0
1
1 5

Sample Output 4

2

It may be optimal to perform no operation.

Sample Input 5

9
0 1 0 1 1 1 0 1 0
3
1 4
5 8
6 7

Sample Output 5

3

Sample Input 6

15
1 1 0 0 0 0 0 0 1 0 1 1 1 0 0
9
4 10
13 14
1 7
4 14
9 11
2 6
7 8
3 12
7 13

Sample Output 6

5

Sample Input 7

10
0 0 0 1 0 0 1 1 1 0
7
1 4
2 5
1 3
6 7
9 9
1 5
7 9

Sample Output 7

1

Solution in Rust (1.15.1) (judge verdict: Accepted)

// https://atcoder.jp/contests/arc085/tasks/arc085_d
//
#![allow(unused_imports)]
use std::io::*;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, [ next / $t:tt ]) => {
        {
            let len = read_value!($iter, usize);
            (0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
        }
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! dvec {
    ($t:expr ; $len:expr) => {
        vec![$t; $len]
    };

    ($t:expr ; $len:expr, $($rest:expr),*) => {
        vec![dvec!($t; $($rest),*); $len]
    };
}

#[allow(unused_macros)]
macro_rules! ifv {
    ($t:expr, $a:expr, $b: expr) => {
        if $t { $a } else { $b }
    }
}

#[allow(unused_macros)]
macro_rules! fill {
    ($t:expr, $v:expr) => {
        for i in 0..$t.len() {
            $t[i] = $v;
        }
    };
}

#[allow(unused_macros)]
macro_rules! join {
    ($t:expr, $glue:expr) => {
        $t.into_iter().map(|w| w.to_string()).collect::<Vec<_>>().join($glue)
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}
// ===


use std::rc::Rc;
type Merger<T> = Rc<Fn(T, T) -> T>;

struct SegmentTree<T> {
    n: usize,
    default: T,
    lazy_default: T,
    bottom_offset: usize,
    data: Vec<T>,
    lazy: Vec<T>,
    merger: Merger<T>,
    lazy_merger: Merger<T>,
}

impl<T: Copy + Eq> SegmentTree<T> {
    fn new(n: usize, initial: T, merger: Merger<T>, lazy_initial: T, lazy_merger: Merger<T>) -> Self {
        let z = (8u32 * std::mem::size_of::<usize>() as u32) - n.leading_zeros();
        let size = (1<<z) as usize;
        SegmentTree {
            n: size*2,
            default: initial,
            lazy_default: lazy_initial,
            bottom_offset: size,
            data: vec![initial; size*2],
            lazy: vec![lazy_initial; size*2],
            merger: merger,
            lazy_merger: lazy_merger
        }
    }

    /// Compute value [i, j).
    fn compute_range(&mut self, i: usize, j: usize) -> T {
        let m = self.bottom_offset;
        self.inner_compute_range(i, j, 1, 0, m)
    }

    fn inner_compute_range(&mut self, i: usize, j: usize, idx: usize, begin: usize, end: usize) -> T {
        self.propagate(idx);

        if end <= i || j <= begin {
            return self.default;
        } else if i <= begin && end <= j {
            return self.data[idx];
        }
        let center = (begin+end)/2;
        let l = self.inner_compute_range(i, j, idx*2, begin, center);
        let r = self.inner_compute_range(i, j, idx*2+1, center, end);
        (self.merger)(l, r)
    }

    /// Apply given value to [i, j).
    fn apply_range(&mut self, i: usize, j: usize, value: T) {
        let m = self.bottom_offset;
        self.inner_apply_range(i, j, value, 1, 0, m);
    }

    fn inner_apply_range(&mut self, i: usize, j: usize, value: T, idx: usize, begin: usize, end: usize) {
        self.propagate(idx);

        if end <= i || j <= begin {
            return;
        } else if i <= begin && end <= j {
            self.lazy[idx] = (self.lazy_merger)(self.lazy[idx], value);
            self.propagate(idx);
            return;
        }
        let center = (begin+end)/2;
        self.inner_apply_range(i, j, value, idx*2, begin, center);
        self.inner_apply_range(i, j, value, idx*2+1, center, end);
        self.data[idx] = (self.merger)(self.data[idx*2], self.data[idx*2+1]);
    }

    fn merge(&mut self, i: usize, j: usize) -> T {
        (self.merger)(self.data[i], self.data[j])
    }

    fn propagate(&mut self, idx: usize) {
        if self.lazy[idx] == self.lazy_default {
            return;
        }
        self.data[idx] = (self.lazy_merger)(self.data[idx], self.lazy[idx]);
        if idx*2+1 < self.lazy.len() {
            self.lazy[idx*2] = (self.lazy_merger)(self.lazy[idx*2], self.lazy[idx]);
            self.lazy[idx*2+1] = (self.lazy_merger)(self.lazy[idx*2+1], self.lazy[idx]);
        }
        self.lazy[idx] = self.lazy_default;
    }
}



// ====

fn set_value_if_lower(seg: &mut SegmentTree<i32>, i: usize, t: i32) {
    let now = seg.compute_range(i, i+1);
    let diff = t-now;
    if diff < 0 {
        seg.apply_range(i, i+1, diff);
    }
}

fn main() {
    input! {
        n: usize,
        b: [i32; n],
        q: usize,
        ranges: [(usize1, usize1); q]
    };
    let mut events = vec![vec![]; n];
    for i in 0..q {
        let (l, r) = ranges[i];
        events[l].push(r);
    }
    for i in 0..n {
        events[i].sort();
        events[i].reverse();
    }

    let mut w = (n+10) as i32;
    let mut segtree = SegmentTree::new(n+10, w, Rc::new(|i, j| min(i, j)), 0, Rc::new(|i, j| i + j));
    segtree.apply_range(0, 1, -w);

    for i in 0..n {
        for &j in &events[i] {
            let best = segtree.compute_range(i, j+1);
            set_value_if_lower(&mut segtree, j+1, best);
        }
        let cost = segtree.compute_range(i, i+1) + ifv!(b[i] == 1, 1, -1);
        set_value_if_lower(&mut segtree, i+1, cost);
    }

    let mut zero = 0;
    for i in 0..n {
        if b[i] == 0 {
            zero += 1;
        }
    }
    println!("{}", zero + segtree.compute_range(n, n+1));
}