Scanf.scanf "%d" (fun d ->
    let c = Array.init 26 (fun _ -> Scanf.scanf " %d" (fun c -> c)) in
    let s = Array.init d (fun _ ->
        Array.init 26 (fun _ ->
            Scanf.scanf " %d" (fun s -> s)))
    in
    let t = Array.init d (fun _ -> Scanf.scanf " %d" (fun t -> t - 1)) in
    let basicsat =
        let rec loop i acc =
            if i = d then acc else loop (i + 1) (acc + s.(i).(t.(i)))
        in
        loop 0 0
    in
    let module S = Set.Make (struct type t = int let compare = compare end) in
    let last = Array.make 26 (S.add d @@ S.singleton (-1)) in
    Array.iteri (fun i t -> last.(t) <- S.add i last.(t)) t;

    let f a = a * (a - 1) / 2 in

    let reducesat =
        let calc set =
            let rec loop prev acc = function
            | [] -> acc
            | hd :: tl -> loop hd (acc + f (hd - prev)) tl
            in
            match S.elements set with
            | hd :: tl -> loop hd 0 tl
            | [] -> 0
        in
        let rec loop i acc =
            if i = 26 then acc else loop (i + 1) (acc + c.(i) * calc last.(i))
        in
        loop 0 0
    in
    Scanf.scanf " %d" (fun m ->
        let rec loop i score =
            if i = m then score else
                let score = Scanf.scanf " %d %d" (fun a b ->
                    let a, b = a - 1, b - 1 in
                    let pre = t.(a) in
                    let p1, _, p2 = S.split a last.(pre) in
                    let p1m = S.max_elt p1 in
                    let p2m = S.min_elt p2 in
                    let score = score + c.(pre) * (f (a - p1m) + f (p2m - a) - f (p2m - p1m)) in
                    let score = score - s.(a).(pre) in
                    last.(pre) <- S.remove a last.(pre);

                    let p1, _, p2 = S.split a last.(b) in
                    let p1m = S.max_elt p1 in
                    let p2m = S.min_elt p2 in
                    let score = score + c.(b) * (- f (a - p1m) - f (p2m - a) + f (p2m - p1m)) in
                    let score = score + s.(a).(b) in
                    last.(b) <- S.add a last.(b);
                    t.(a) <- b;
                    score
                )
                in
                let () = Printf.printf "%d\n" score in
                loop (i + 1) score
        in
        loop 0 (basicsat - reducesat)
    )
)