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::io::Write;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

#[allow(unused_macros)]
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)*}
    };
}

#[allow(unused_macros)]
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)*}
    };

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

#[allow(unused_macros)]
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, switch) => {
        {
            let ty = read_value!($iter, i32);
            if ty == 1 {
                vec![ty, read_value!($iter, i32), read_value!($iter, i32)]
            } else if ty == 2 {
                vec![ty, read_value!($iter, i32)]
            } else {
                vec![ty, read_value!($iter, i32)]
            }
        }
    };

    ($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,
    bottom_offset: usize,
    data: Vec<T>,
    merger: Merger<T>,
}

impl<T: Debug + Copy + Eq> SegmentTree<T> {
    fn new(n: usize, initial: T, 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,
            bottom_offset: size,
            data: vec![initial; size*2],
            merger: merger,
        }
    }

    /// Change single position [i, i+1) to value v.
    fn set(&mut self, i: usize, v: T) {
        let mut idx = self.bottom_offset + i;
        self.data[idx] = v;
        while idx >= 1 {
            idx /= 2;
            self.data[idx] = (self.merger)(self.data[idx*2], self.data[idx*2+1]);
        }
    }

    /// Get single position value.
    fn get(&mut self, i: usize) -> T {
        self.data[self.bottom_offset+i]
    }

    /// Apply merge with v to single position [i, i+1).
    fn apply(&mut self, i: usize, v: T) {
        let mut idx = self.bottom_offset + i;
        while idx >= 1 {
            self.data[idx] = (self.merger)(self.data[idx], v);
            idx /= 2;
        }
    }

    /// Compute value [i, j).
    fn compute_range(&self, mut i: usize, mut j: usize) -> T {
        if i >= j {
            return self.default;
        }
        let mut result_left = self.default;
        let mut result_right = self.default;
        i += self.bottom_offset;
        j += self.bottom_offset;
        while i != j {
            if i & 1 == 1 {
                result_left = (self.merger)(result_left, self.data[i]);
                i += 1;
            }
            if j & 1 == 1 {
                j -= 1;
                result_right = (self.merger)(self.data[j], result_right);
            }
            i >>= 1;
            j >>= 1;
        }
        (self.merger)(result_left, result_right)
    }

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

    fn debug_print(&self, from: usize, to: usize) {
        for i in from..to {
            debug!(i, self.data[self.bottom_offset+i]);
        }
        debug!(from, to, self.compute_range(from, to));
    }
}

// ====

const INF: i32 = 100000000;

fn main() {
    input! {
        n: usize,
        a: [i32; n],
        q: usize,
        ranges: [(usize1, usize); q]
    };

    let mut pos = vec![vec![]; n+1];
    for (l, r) in ranges {
        pos[l].push(r);
    }


    let mut seg0 = SegmentTree::new(n+10, -INF, Rc::new(|a,b| max(a,b)));
    let mut seg1 = SegmentTree::new(n+10, -INF, Rc::new(|a,b| max(a,b)));
    seg0.set(0, 0);
    seg1.set(0, 0);
    for f in 0..n {
        let now = seg0.compute_range(f, f+1);
        for &t in &pos[f] {
            let a = max(now, seg1.compute_range(f, t));
            // debug!(f, t, now, a);
            let c = seg1.compute_range(t, t+1);
            seg1.set(t, max(c, a));
        }
        let step = max(seg0.compute_range(f, f+1), seg1.compute_range(f, f+1)) + ifv!(a[f] == 0, 1, -1);
        seg0.set(f+1, step);
    }

    let mut w = max(seg0.compute_range(n, n+1), seg1.compute_range(n, n+1));
    for i in 0..n {
        if a[i] == 1 {
            w += 1;
        }
    }
    w = (n as i32) - w;
    println!("{}", w);
}