Problem:
 (Please read problem A first. The maximum score you can get by solving this problem C is 1, which will have almost no effect on your ranking.)    Beginner's Guide "Local search" is a powerful method for finding a high-quality solution.
In this method, instead of constructing a solution from scratch, we try to find a better solution by slightly modifying the already found solution.
If the solution gets better, update it, and if it gets worse, restore it.
By repeating this process, the quality of the solution is gradually improved over time.
The pseudo-code is as follows.  solution = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
    slightly modify the solution (randomly)
    if the solution gets worse:
        restore the solution  For example, in this problem, we can use the following modification: pick the date d and contest type q at random and change the type of contest to be held on day d to q .
The pseudo-code is as follows.  t[1..D] = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
    pick d and q at random
    old = t[d] # Remember the original value so that we can restore it later
    t[d] = q
    if the solution gets worse:
        t[d] = old  The most important thing when using the local search method is the design of how to modify solutions.   If the amount of modification is too small, we will soon fall into a dead-end (local optimum) and, conversely, if the amount of modification is too large, the probability of finding an improving move becomes extremely small.  In order to increase the number of iterations, it is desirable to be able to quickly calculate the score after applying a modification.   In this problem C, we focus on the second point.
The score after the modification can, of course, be obtained by calculating the score from scratch.
However, by focusing on only the parts that have been modified, it may be possible to quickly compute the difference between the scores before and after the modification.
From another viewpoint, the impossibility of such a fast incremental calculation implies that a small modification to the solution affects a majority of the score calculation.
In such a case, we may need to redesign how to modify solutions, or there is a high possibility that the problem is not suitable for local search.
Let's implement fast incremental score computation.
It's time to demonstrate the skills of algorithms and data structures you have developed in ABC and ARC!  In this kind of contest, where the objective is to find a better solution instead of the optimal one, a bug in a program does not result in a wrong answer, which may delay the discovery of the bug.
For early detection of bugs, it is a good idea to unit test functions you implemented complicated routines.
For example, if you implement fast incremental score calculation, it is a good idea to test that the scores computed by the fast implementation match the scores computed from scratch, as we will do in this problem C.      Problem Statement You will be given a contest schedule for D days and M queries of schedule modification.
In the i -th query, given integers d_i and q_i , change the type of contest to be held on day d_i to q_i , and then output the final satisfaction at the end of day D on the updated schedule.
Note that we do not revert each query. That is, the i -th query is applied to the new schedule obtained by the (i-1) -th query.        Input Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A and the queries.  D  c_1  c_2  \cdots  c_{26}  s_{1,1}  s_{1,2}  \cdots  s_{1,26}  \vdots  s_{D,1}  s_{D,2}  \cdots  s_{D,26}  t_1  t_2  \vdots  t_D  M  d_1  q_1  d_2  q_2  \vdots  d_M  q_M    The constraints and generation methods for the input part are the same as those for Problem A.  For each d=1,\ldots,D , t_d is an integer generated independently and uniformly at random from {1,2,\ldots,26} .  The number of queries M is an integer satisfying 1\leq M\leq 10^5 .  For each i=1,\ldots,M , d_i is an integer generated independently and uniformly at random from {1,2,\ldots,D} .  For each i=1,\ldots,26 , q_i is an integer satisfying 1\leq q_i\leq 26 generated uniformly at random from the 25 values that differ from the type of contest on day d_i .       Output Let v_i be the final satisfaction at the end of day D on the schedule after applying the i -th query.
Print M integers v_i to Standard Output in the following format:  v_1  v_2  \vdots  v_M         Sample Input 1 5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192
1
17
13
14
13
5
1 7
4 11
3 4
5 24
4 19      Sample Output 1 72882
56634
38425
27930
42884  Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case.      Next Step Let's go back to Problem A and implement the local search algorithm by utilizing the incremental score calculator you just implemented!
For this problem, the current modification "pick the date d and contest type q at random and change the type of contest to be held on day d to q " is actually not so good. By considering why it is not good, let's improve the modification operation.
One of the most powerful and widely used variant of the local search method is "Simulated Annealing (SA)", which makes it easier to reach a better solution by stochastically accepting worsening moves.
For more information about SA and other local search techniques, please refer to the editorial that will be published after the contest.

Solution (Python):
import sys, heapq

def calcScore_change(D, complaints, satisfications, HoldedContestDays, N_queues, queues):
    TotalSatisfication = 0
    ContestDays_List = [ [i+1] * 26 for i in range(D) ] 

    complaint_all = 0
    for i in range(26):
        complaint_all += complaints[i]

    complaint_sum = 0
    for i in range(D):
        complaint_sum += complaint_all
        Contest = HoldedContestDays[i]
        complaint_sum -= ContestDays_List[i][Contest] * complaints[Contest]
        ContestDays_List[i][Contest] = 0

        TotalSatisfication += satisfications[i][Contest] - complaint_sum

        for j in range(i+1, D):
            ContestDays_List[j][Contest] = ContestDays_List[j-1][Contest] + 1

    scores_afterchanging = [TotalSatisfication]
    for m in range(N_queues):
        queue = queues[m]

        day = queue[0]
        contest_change = queue[1]
        contest_old = HoldedContestDays[day]

        
        nextcontest = D
        for i in range(day+1, D):
            if(HoldedContestDays[i]==contest_old):
                nextcontest = i
                break
        for i in range(day, nextcontest):
            if(i==0):
                ContestDays_List[i][contest_old] = 1
            else:
                ContestDays_List[i][contest_old] = ContestDays_List[i-1][contest_old]+1
        if(day==0):
            changed_s = 1
        else:
            changed_s = ContestDays_List[day-1][contest_old]+1

        score_change = -changed_s * (nextcontest-day) * complaints[contest_old]

        
        nextcontest_new = D
        for i in range(day+1, D):
            if(HoldedContestDays[i]==contest_change):
                nextcontest_new = i
                break
        k = 0
        for i in range(day, nextcontest_new):
            ContestDays_List[i][contest_change] = k
            k+= 1
        if(day==0):
            changed_s2 = 1
        else:
            changed_s2 = ContestDays_List[day-1][contest_change]+1
        change = changed_s2 * (nextcontest_new-day) * complaints[contest_change]
        score_change += change

        
        score_change += satisfications[day][contest_change] - satisfications[day][contest_old]

        score = scores_afterchanging[-1] + score_change
        scores_afterchanging.append(score)
        HoldedContestDays[day] = contest_change
    return scores_afterchanging
    """
    TotalSatisfication: 変更前のスコア
    di Contest ->qiに変更すると:
        もとのHoldedContestDays, ContestDays_Listの変更を忘れないように

        元のコンテストContestからqiへ変更
        1) ContestDays_List[d][Contest] = ContestDays_List[d-1][Contest] +1になる(次にコンテストが行われ0に初期化される日をd_nextとするとd_next-1まで)
        結果、満足度は (ContestDays_List[di-1][Contest]+1) * (d_next-di) * complaints[Contest]現象

        2)その代わり実行されたコンテストは(qiの次の実行びをd_next_2として)
        (ContestDays_List[di-1][qi]+1) * (d_next_2-di) * complaints[qi]増加

        3)さらに、s[di][qi]-s[di][Contest]上昇
          5 0 1 2 3 0
        ->5 6 7 8 9 0
    """










"""
13: 19922, 89
20: 19830, 80

20: 19830 - 80 * 5 = 19430
13: 19922 - 89 * 2 = 19744
毎日1つのコンテスト
満足度をあげるようにコンテスト
ci * (最後にコンテストを行ってからの経過日数)満足度低下
上昇値はs_d_i

"""
if(__name__ == "__main__"):
    D = int(input().strip())
    complaints = list(map(int, input().split() ) )

    satisfications = []
    for i in range(D):
        satisfication = list(map(int, input().split() ) )
        satisfications.append(satisfication)
    HoldedContestDays =[0] * D
    for i in range(D):
        HoldedContestDays[i] = int(input().strip())
        HoldedContestDays[i] -= 1
    N_queues = int(input().strip())
    queues = []
    for m in range(N_queues):
        queue = list(map(int, input().split() ) )
        queue[0] -= 1
        queue[1] -= 1
        queues.append(queue)
    Score_change = calcScore_change(D, complaints, satisfications, HoldedContestDays, N_queues, queues)

    for m in range(N_queues):
        print(Score_change[m+1])

Solution (Python):
D = int(input())
C = [int(x) for x in input().split()]
S = [[int(i) for i in input().split()] for D in range(D)]
T = [0]*D
for i in range(D):
    T[i] = int(input())
M = int(input())
dp = [[int(i) for i in input().split()] for M in range(M)]

score = [0]*26
last = [-1]*26

for i in range(D):
    score[T[i]-1] += S[i][T[i]-1]
    last[T[i]-1] = i

    for j in range(26):
        score[j] -= C[j]*(i-last[j])

for k in range(M):
    x = T[dp[k][0]-1]
    y = dp[k][1]
    T[dp[k][0]-1] = y
    score[x-1] = 0
    score[y-1] = 0
    last[x-1] = -1
    last[y-1] = -1
    for i in range(D):
        if T[i] == x or T[i] == y:
            score[T[i]-1] += S[i][T[i]-1]
            last[T[i]-1] = i

        score[x-1] -= C[x-1]*(i-last[x-1])
        score[y-1] -= C[y-1]*(i-last[y-1])

    print(sum(score))

Solution (Python):
import numpy as np
from bisect import bisect_left

D = int(input())
C = np.array(list(map(int, input().split())))
S = np.array([list(map(int, input().split())) for d in range(D)])

L = np.empty(26, int)
L[:] = -1

X = [[-1] for _ in range(26)]
T = []

score = 0
for d in range(D):
    t = int(input())-1
    T.append(t)
    L[t] = d
    score += S[d, t] - np.dot(C, d-L)
    X[t].append(d)

for x in X:
    x.append(D)
    
M = int(input())
for _ in range(M):
    d, q = map(int, input().split())
    d-=1
    q-=1

    t = T[d]
    T[d] = q
    
    i = bisect_left(X[t], d)
    d_prev = X[t][i-1]
    d_next = X[t][i+1]
    
    dd = d-d_prev-1
    score += C[t]*(dd+1)*dd//2
    dd = d_next-d-1
    score += C[t]*(dd+1)*dd//2
    dd = d_next-d_prev-1
    score -= C[t]*(dd+1)*dd//2

    X[t].pop(i)
    
    i = bisect_left(X[q], d)
    d_prev = X[q][i-1]
    d_next = X[q][i]
    
    dd = d-d_prev-1
    score -= C[q]*(dd+1)*dd//2
    dd = d_next-d-1
    score -= C[q]*(dd+1)*dd//2
    dd = d_next-d_prev-1
    score += C[q]*(dd+1)*dd//2

    X[q].insert(i, d)

    score += S[d,q] - S[d,t]

    print(score)

Solution (Python):
d = int(input())
c = list(map(int, input().split()))
s = [list(map(int, input().split())) for _ in range(d)]
t = [int(input()) - 1 for _ in range(d)]

def scoring(d, c, s, t):
    v = []
    memo = [0 for _ in range(26)]
    for i in range(d):
        if i == 0:
            score = 0
        else:
            score = v[-1]
        score += s[i][t[i]]
        memo[t[i]] = i + 1
        for j in range(26):
            score -= c[j] * (i+1 - memo[j])

        v.append(score)

    return v[-1]

score = scoring(d, c, s, t)

m = int(input())
memo = [[0 for _ in range(26)]]
for i in range(d):
    l = memo[-1]
    l[t[i]] = i+1
    memo.append(l)

for _ in range(m):
    x, y = map(int, input().split())
    x -= 1
    y -= 1
    before_ti, after_ti = 0, d+1
    before_y, after_y = 0, d+1

    for i in range(x):
        if t[i] == t[x]:
            before_ti = i+1
        if t[i] == y:
            before_y = i+1

    for i in range(x+1, d):
        if t[i] == t[x]:
            after_ti = i+1
            break
    for i in range(x+1, d):
        if t[i] == y:
            after_y = i+1
            break

    score -= s[x][t[x]]
    score += s[x][y]
    score -= c[t[x]] * (x + 1 - before_ti) * (after_ti - x - 1)
    score += c[y] * (x + 1 - before_y) * (after_y - x - 1)

    t[x] = y

    print(score)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))


D = ini()
C = inl()
assert len(C) == 26
S = [None] * D
for i in range(D):
    S[i] = inl()
    assert len(S[i]) == 26
T = [ini() - 1 for _ in range(D)]
changes = []
M = ini()
for i in range(M):
    d, q = inm()
    d -= 1
    q -= 1
    changes.append((d, q))



def main():
    last = [[-1] * (D + 1) for _ in range(26)]
    score = 0
    for d in range(D):
        ct = T[d]
        score += S[d][ct]
        for i in range(26):
            last[i][d + 1] = last[i][d]
        last[ct][d + 1] = d
        for i in range(26):
            score -= C[i] * (d - last[i][d + 1])

    for d, after in changes:
        before = T[d]
        if before == after:
            continue
        score -= S[d][before]
        score += S[d][after]
        lb = last[before][d]
        la = last[after][d]
        da = db = 0
        for x in range(d, D):
            if x > d and T[x] == before:
                break
            last[before][x + 1] = lb
            db += 1
        score -= C[before] * (d - lb) * db
        for x in range(d, D):
            if T[x] == after:
                break
            last[after][x + 1] = d
            da += 1
        score += C[after] * (d - la) * da
        T[d] = after
        print(score)


main()

Solution (Python):

import sys
def main(D, C, S, T, M, Q):
    def evaluate(i, t, satisfaction, last):
        satisfaction += S[i][t]
        last[t] = i
        for j, c in enumerate(C):
            satisfaction -= c * (i - last[j])
        return (satisfaction, last)

    satisfaction = 0
    last = [-1] * 26
    count = [BinaryIndexedTree(D) for _ in range(26)]
    for i, t in enumerate(T):
        satisfaction, last = evaluate(i, t, satisfaction, last)
        count[t].add(i, 1)

    for d, new in Q:
        old = T[d]
        satisfaction += S[d][new] - S[d][old]
        cnt_old = count[old].query(d)
        nxt_d_old = count[old].bisect(lambda x: x < cnt_old + 1)
        pre_d_old = count[old].bisect(lambda x: x < cnt_old - 1) if cnt_old > 1 else -1
        satisfaction -= C[old] * (nxt_d_old - d) * (d - pre_d_old)
        T[d] = new
        count[old].add(d, -1)
        count[new].add(d, 1)
        cnt_new = count[new].query(d)
        nxt_d_new = count[new].bisect(lambda x: x < cnt_new + 1)
        pre_d_new = count[new].bisect(lambda x: x < cnt_new - 1) if cnt_new > 1 else -1
        satisfaction += C[new] * (nxt_d_new - d) * (d - pre_d_new)
        print(satisfaction)

class BinaryIndexedTree:
    def __init__(self, n=None, f=lambda x, y: x + y, identity=0, initial_values=None):
        assert(n or initial_values)
        self.__f, self.__id, = f, identity
        self.__n = len(initial_values) if initial_values else n
        self.__d = [identity] * (self.__n + 1)
        if initial_values:
            for i, v in enumerate(initial_values): self.add(i, v)

    def add(self, i, v):
        n, f, d = self.__n, self.__f, self.__d
        i += 1
        while i <= n:
            d[i] = f(d[i], v)
            i += -i & i

    def query(self, r):
        res, f, d = self.__id, self.__f, self.__d
        r += 1
        while r:
            res = f(res, d[r])
            r -= -r & r
        return res

    def bisect(self, func):
        n, f, d, v = self.__n, self.__f, self.__d, self.__id
        x, i = 0, 1 << (n.bit_length() - 1)
        while i > 0:
            if x + i <= n and func(f(v, d[x + i])): v, x = f(v, d[x + i]), x + i
            i >>= 1
        return x

if __name__ == '__main__':
    input = sys.stdin.readline
    D = int(input())
    *C, = map(int, input().split())
    S = [list(map(int, input().split())) for _ in range(D)]
    T = [int(input()) - 1 for _ in range(D)]
    M = int(input())
    Q = [tuple(map(lambda x:int(x) - 1, input().split())) for _ in range(M)]
    main(D, C, S, T, M, Q)

Solution (Python):
from time import time
from random import randrange
from bisect import bisect_left
import sys
def input():
	return sys.stdin.buffer.readline()[:-1]
start = time()
d = int(input())
c = list(map(int, input().split()))
C = sum(c)
s = [list(map(int, input().split())) for _ in range(d)]

t = []
day = [[0] for _ in range(26)]
order = []

def score(t):
	res = 0
	minus = 0
	last = [0 for _ in range(26)]
	for i, x in enumerate(t):
		minus += C - c[x-1] * (i - last[x-1] + 1)
		res -= minus
		res += s[i][x-1]
		last[x-1] = i+1
		
	return res

def tri(n):
	return n * (n-1) // 2

def change(i, to):
	diff = 0
	fr = t[i]-1
	
	
	if fr == to:
		return 0
	fr_ind = bisect_left(day[fr], i+1)
	diff += (tri(day[fr][fr_ind] - day[fr][fr_ind-1]) + tri(day[fr][fr_ind+1] - day[fr][fr_ind])) * c[fr]
	diff -= (tri(day[fr][fr_ind+1] - day[fr][fr_ind-1])) * c[fr]
	diff -= s[i][fr]
	
	to_ind = bisect_left(day[to], i+1)
	diff += (tri(day[to][to_ind] - day[to][to_ind-1])) * c[to]
	diff -= (tri(day[to][to_ind] - (i+1)) + tri(i+1 - day[to][to_ind-1])) * c[to]
	diff += s[i][to]

	
	day[fr].pop(fr_ind)
	after = day[to][:to_ind] + [i+1] + day[to][to_ind:]
	day[to] = after
	t[i] = to+1
	
	
	
	return diff
	
		


res = 0
minus = 0
last = [0 for _ in range(26)]
for i in range(d):
	minus += C
	
	
	
	M_ind = int(input())-1
	minus -= c[M_ind] * (i - last[M_ind] + 1)
	last[M_ind] = i+1
	res -= minus - s[i][M_ind]
	t.append(M_ind+1)
	day[M_ind].append(i+1)

for i in range(26):
	day[i].append(d+1)






for _ in range(int(input())):
	d, q = map(int, input().split())
	res += change(d-1, q-1)
	print(res)

Solution (Python):
import sys
input = lambda: sys.stdin.buffer.readline()

L = 26
D = int(input())
C = list(map(int, input().split()))
S = [list(map(int, input().split())) for _ in range(D)]

T = [int(input()) for _ in range(D)]

M = int(input())

class BinaryIndexedTree:
    def __init__(self, n):
        self.n = n
        self.data = [0] * (self.n+1)
    
    def sum(self, i):
        res = 0
        while i > 0:
            res += self.data[i]
            i -= i & -i
        return res
    
    def add(self, i, x):
        if i <= 0: raise IndexError
        while i <= self.n:
            self.data[i] += x
            i += i & -i
    
    def lower_bound(self, x):
        if x <= 0: return 0
        cur, s, k = 0, 0, 1 << (self.n.bit_length()-1)
        while k:
            nxt = cur + k 
            if nxt <= self.n and s + self.data[nxt] < x:
                s += self.data[nxt]
                cur = nxt
            k >>= 1
        return cur + 1

def rsum(x):
    return x*(x+1)//2

b = [BinaryIndexedTree(D) for _ in range(L)]

score = 0
for d, cont in enumerate(T):
    cont -= 1
    b[cont].add(d+1, 1)
    score += S[d][cont]

for i in range(L):
    m = b[i].sum(D)
    tmp = 0
    s = [0]
    for j in range(1, m+1):
        s.append(b[i].lower_bound(j))
    s.append(D+1)

    for j in range(len(s)-1):
        x = s[j+1] - s[j] - 1
        tmp += rsum(x)
    
    score -= tmp*C[i]


def chg(d, q):
    diff = 0
    p = T[d]-1
    d += 1

    o = b[p].sum(d)
    d1 = b[p].lower_bound(o-1)
    d2 = b[p].lower_bound(o+1)

    diff += rsum(d-d1) * C[p]
    diff += rsum(d2-d) * C[p]
    diff -= rsum(d2-d1) * C[p]

    o = b[q].sum(d)
    d1 = b[q].lower_bound(o)
    d2 = b[q].lower_bound(o+1)

    diff += rsum(d2-d1) * C[q]
    diff -= rsum(d-d1) * C[q]
    diff -= rsum(d2-d) * C[q]

    b[p].add(d, -1)
    b[q].add(d, 1)

    d -= 1
    T[d] = q+1
    diff -= S[d][p]
    diff += S[d][q] 

    return diff

for _ in range(M):
    d, q = map(lambda x: int(x)-1, input().split())
    diff = chg(d, q)
    score += diff
    print(score)

Solution (Python):
D = int(input())
c = list(map(int, input().split()))
s = [list(map(int, input().split())) for _ in range(D)]
t = [int(input()) - 1 for _ in range(D)]
M = int(input())

d = []
q = []
for _ in range(M):
    d_, q_ = map(int, input().split())
    d.append(d_ - 1)
    q.append(q_ - 1)

N = 26


def calc_score(t):
    scores = [0] * N
    last = [-1] * N
    for d in range(D):
        last[t[d]] = d
        scores[t[d]] += s[d][t[d]]

        for i in range(N):
            if last[t[d]] != -1:
                scores[i] -= c[i] * (d - last[i])
    return sum(scores)


score = calc_score(t)


for di, qi in zip(d, q):
    
    old_type = t[di]

    for next_d in range(di + 1, D):
        if t[next_d] == old_type:
            break
    else:
        next_d = D

    for prev_d in range(di - 1, -1, -1):
        if t[prev_d] == old_type:
            break
    else:
        prev_d = -1

    score -= s[di][old_type]
    score -= (next_d - di) * (di - prev_d) * c[old_type]

    
    for next_d in range(di + 1, D):
        if t[next_d] == qi:
            break
    else:
        next_d = D

    for prev_d in range(di - 1, -1, -1):
        if t[prev_d] == qi:
            break
    else:
        prev_d = -1

    score += s[di][qi]
    score += (next_d - di) * (di - prev_d) * c[qi]

    print(score)

    t[di] = qi

Solution (Python):
D=int(input())
c=input().split()
c=[int(a) for a in c]
S=[]
for _ in range(D):
    s=input().split()
    s=[int(a) for a in s]
    S.append(s)
T=[]
for _ in range(D):
    t=int(input())-1
    T.append(t)
M=int(input())
numbers=[]
for _ in range(M):
    d,q=map(int,input().split())
    numbers.append([d,q])
whole=sum(c)
for m in range(M):
    ans = 0
    held = [0 for _ in range(26)]
    e=numbers[m][0]-1
    q=numbers[m][1]-1
    a=T[e]
    T[e]=q
    wholes=0
    for d in range(D):
        s = S[d]
        place = T[d]
        ans += s[place]
        wholes+=whole
        wholes-=c[place]*((d+1)-held[place])
        held[place] = d + 1
        ans-=wholes
    print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(2 * 10**6)


def inpl():
    return list(map(int, input().split()))


def count_v(last_d, C, S, t, d):
    ret = S[t - 1]
    last_d[t - 1] = d
    for i in range(len(last_d)):
        ret -= C[i] * (d - last_d[i])
    return ret


def count_v_virtual(last_d, C, S, t, d):
    ret = S[t]
    tmp = last_d[t]
    last_d[t] = d
    for i in range(len(last_d)):
        ret -= C[i] * (d - last_d[i])
    last_d[t] = tmp
    return ret


def main():
    D = int(input())
    C = inpl()
    Ss = [inpl() for _ in range(D)]
    T = [int(input()) for _ in range(D)]
    M = int(input())
    DQ = [inpl() for _ in range(M)]
    last_d = [-1] * len(C)
    Contest = 26

    v = 0
    for d in range(D):
        tmp = count_v(last_d, C, Ss[d], T[d], d)
        v += tmp
        

    for d, q in DQ:
        diff = 0
        original_t = T[d - 1]
        last_d_q = 0
        last_d_ori = 0
        for i in range(d):
            if T[i] == q:
                last_d_q = i + 1
            if T[i] == original_t and i < d - 1:
                last_d_ori = i + 1
        
        for i in range(d - 1, D):
            if T[i] == q:
                break
            diff += C[q - 1] * (d - last_d_q)
        
        T[d - 1] = q
        for i in range(d - 1, D):
            if T[i] == original_t:
                break
            diff -= C[original_t - 1] * (d - last_d_ori)
        
        v += diff + Ss[d - 1][q - 1] - Ss[d - 1][original_t - 1]
        print(v)
    return


if __name__ == '__main__':
    main()

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





D = I()
C = IL()
S = ILL(D)

ans = 0
score = 0
last = [[-1] for i in range(26)]
schedule = []

for d in range(D):
  t = I()-1
  last[t].append(d)
  score += S[d][t]
  schedule.append(t)

for i in range(26):
  last[i].append(D)
  for k in range(len(last[i])-1):
    g = last[i][k+1]-last[i][k]-1
    score -= C[i]*g*(g+1)//2

M = I()

for _ in range(M):
  d,q = IL()
  d,q =  d-1,q-1
  p = schedule[d]
  schedule[d] = q
  score -= S[d][p]
  score += S[d][q]
  
  pos = last[p].index(d)
  score -= C[p]*(last[p][pos]-last[p][pos-1])*(last[p][pos+1]-last[p][pos])
  last[p].remove(d)
  
  pos = bisect.bisect(last[q],d)
  score += C[q]*(d-last[q][pos-1])*(last[q][pos]-d)
  bisect.insort(last[q],d)
  
  print(score)

Solution (Python):
import heapq
D=int(input())
c=list(map(int,input().split()))
s=[0]
last=[0]*26
for i in range(D):
  s.append(list(map(int,input().split())))
contests=[]
for i in range(26):
  contests.append([])
  contests[-1].append(0)
  contests[-1].append(D+1)
schedule=[0]*(D+1)
score=0
for i in range(1,D+1):
  t=int(input())-1
  score+=s[i][t]
  last[t]=i
  contests[t].append(i)
  schedule[i]=t+1
  for j in range(26):
    score-=c[j]*(i-last[j])
for i in range(26):
  contests[i].sort()
m=int(input())
for i in range(m):
  d,q=map(int,input().split())
  changebefore=schedule[d]-1
  changeafter=q-1
  r=contests[changebefore]
  score-=s[d][changebefore]
  score+=s[d][changeafter]
  for j in range(len(r)-1):
    if r[j]==d:
      score-=c[changebefore]*((r[j+1]-r[j-1]-1)*(r[j+1]-r[j-1]))//2
      score+=c[changebefore]*((r[j+1]-d-1)*(r[j+1]-d))//2
      score+=c[changebefore]*((d-r[j-1]-1)*(d-r[j-1]))//2
      break
  contests[changebefore].remove(d)
  contests[changebefore].sort()
  r=contests[changeafter]
  for j in range(len(r)-1):
    if r[j+1]>d:
      score+=c[changeafter]*((r[j+1]-r[j]-1)*(r[j+1]-r[j]))//2
      score-=c[changeafter]*((r[j+1]-d-1)*(r[j+1]-d))//2
      score-=c[changeafter]*((d-r[j]-1)*(d-r[j]))//2
      break
  contests[changeafter].append(d)
  contests[changeafter].sort()
  schedule[d]=q
  print(score)