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: Wrong Answer)

// ${url}
//
#![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,
    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;
    }
}

// ====
// ====


const INF: i32 = 1000000000;

fn main() {
    input! {
        n: usize, b: [i32; n],
        q: usize,
        ranges: [(usize1, usize1); q]
    };
    let mut ranges = ranges.into_iter().map(|a| (a.0, a.1, 0, 0)).collect::<Vec<_>>();
    // debug!(ranges);

    let mut score_table = vec![0; n];
    for i in 0..n {
        score_table[i] = b[i]*2-1;
    }
    let mut sum = vec![0; n+1];
    for i in 0..n {
        sum[i+1] = sum[i] + score_table[i];
    }

    let mut events_fr = vec![vec![]; n];
    let mut events_to = vec![vec![]; n];
    for i in 0..q {
        let fr = ranges[i].0;
        let to = ranges[i].1;
        events_fr[fr].push(i);
        events_to[to].push(i);
    }
    {
        let mut sidx = 0;
        let mut eidx = 0;
        for i in 0..n {
            for &idx in &events_fr[i] {
                ranges[idx].2 = sidx;
                sidx += 1;
            }
            for &idx in &events_to[i] {
                ranges[idx].3 = eidx;
                eidx += 1;
            }
        }
    }

    let mut inseg = SegmentTree::new(q+100, 0, Rc::new(|a,b| max(a,b)), 0, Rc::new(|a,b| a+b));
    let mut outseg = SegmentTree::new(q+100, 0, Rc::new(|a,b| max(a,b)), 0, Rc::new(|a,b| a+b));

    let mut best_score = 0;
    let mut dp = vec![0; n];
    let mut last_seen = q;

    let mut diff_tbl = 0;
    for i in (0..n).rev() {
        let mut mq = last_seen;
        for &idx in &events_to[i] {
            let &(fr, to, sidx, eidx) = &ranges[idx];
            let in_score = inseg.compute_range(sidx+1, q) + diff_tbl;
            let out_score = outseg.compute_range(eidx+1, q);

            let wv = inseg.compute_range(sidx, sidx+1);
            inseg.apply_range(sidx, sidx+1, max(in_score, out_score)-wv);
            mq = min(mq, eidx);
        }
        last_seen = min(last_seen, mq);

        diff_tbl += score_table[i];

        for &idx in &events_fr[i] {
            let &(fr, to, sidx, eidx) = &ranges[idx];
            let v = inseg.compute_range(sidx, sidx+1);
            best_score = max(best_score, v);
            inseg.apply_range(sidx, sidx+1, -INF);
            outseg.apply_range(eidx, eidx+1, v);
        }
    }

    for i in 0..n {
        best_score += ifv!(b[i] == 0, 1, 0);
    }
    println!("{}", (n as i32) - best_score);
}