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 numpy as np

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

last_day = np.zeros(26, dtype=int)

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

score = 0
for d, t in enumerate(T, 1):
    last_day[t-1] = d
    decrease = c * (d - last_day)
    score += S[d-1, t-1] - decrease.sum()


def calc_pre(ans, pre_t, t, d):
    flag1 = flag2 = True
    res = [-1, -1]
    for day in range(d-1, -1, -1):
        td = ans[day]
        if td == pre_t and flag1:
            res[0] = day
            flag1 = False
        if td == t and flag2:
            res[1] = day
            flag2 = False
        if not (flag1 or flag2):
            return res
    return res

def calc_next(ans, pre_t, t, d):
    flag1 = flag2 = True
    res = [D, D]
    for day in range(d+1, D):
        td = ans[day]
        if td == pre_t and flag1:
            res[0] = day
            flag1 = False
        if td == t and flag2:
            res[1] = day
            flag2 = False
        if not (flag1 or flag2):
            return res
    return res


ans = []
M = int(input())
dq = [list(map(int, input().split())) for i in range(M)]

for d, q in dq:
    d -= 1
    t = T[d]
    dm1, dm2 = calc_pre(T, t, q, d)
    dp1, dp2 = calc_next(T, t, q, d)
    diff = S[d, q-1] - S[d, t-1] + c[t-1]*(dm1-d)*(dp1-d) - c[q-1]*(dm2-d)*(dp2-d)
    score += diff
    ans.append(score)
    T[d] = q

print(*ans, sep='\n')

Solution (Python):
from random import randint
import sys
input = sys.stdin.readline


def calc_score(D, C, S, T):
    """
    開催日程Tを受け取ってそこまでのスコアを返す
    """
    contest_last_opened = [0]*26  
    score = 0
    for d, t in enumerate(T, start=1):
        get_score = S[d-1][t-1]
        score += get_score
        contest_last_opened[t-1] = d
        loss_score = 0
        for i in range(26):
            ld = contest_last_opened[i]
            loss_score += C[i]*(d-ld)
        score -= loss_score
    return score


def update_score(D, C, S, T, score, ct, ci):
    """
    ct日目のコンテストをコンテストciに変更する
    スコアを差分更新する

    ct: change t 変更日
    ci: change i 変更コンテスト
    """
    contest_last_opened = [0]*26  
    for d in range(1, ct):
        contest_last_opened[T[d-1]-1] = d

    prei = T[ct-1]  
    prei_ld = contest_last_opened[prei-1]  
    preci_ld = contest_last_opened[ci-1]  
    score -= S[ct-1][prei-1]
    score += S[ct-1][ci-1]

    for d in range(ct, D+1):
        if d != ct and T[d-1] == prei:
            break
        score += C[prei-1]*(d - ct)
        score -= C[prei-1]*(d - prei_ld)

    for d in range(ct, D+1):
        if d != ct and T[d-1] == ci:
            break
        score += C[ci-1]*(d - preci_ld)
        score -= C[ci-1]*(d - ct)
    T[ct-1] = ci
    return score, T


def local_search():
    pass


def main(D, C, S):
    T = []
    for d in range(1, D+1):
        
        
        
        today_score = calc_score(D, C, S, T + [1])
        today_contest = 1
        for i in range(2, 26 + 1):
            tmp_score = calc_score(D, C, S, T + [i])
            if today_score < tmp_score:
                today_score = tmp_score
                today_contest = i
        T.append(today_contest)
    return T


if __name__ == '__main__':
    D = int(input())
    C = [int(i) for i in input().split()]
    S = [[int(i) for i in input().split()] for j in range(D)]
    T = [int(input()) for i in range(D)]
    M = int(input())
    DQ = [[int(i) for i in input().split()] for j in range(M)]
    score = calc_score(D, C, S, T)
    for d, q in DQ:
        score, T = update_score(D, C, S, T, score, d, q)
        print(score)

Solution (Python):
NTEST = 26

D=int(input())

C=list(map(int,input().split()))

SL=list()
SL.append([0 for i in range(NTEST)])
for d in range(D):
    S=list(map(int,input().split()))
    SL.append(S)

tests=list()
tests.append(0)
for d in range(D):
    tests.append(int(input()))

def calcSat(test_applied):
    lastDay = [0 for i in range(NTEST)]

    sat = 0
    for d in range(1,D+1):
        tst = test_applied[d] - 1
        lastDay[tst] = d
        sat += SL[d][tst]
        for itst in range(NTEST):
            sat -= C[itst] * (d-lastDay[itst])
    return sat

satList = list()
satList.append(0)
lastDay = [[0 for i in range(NTEST)]]

def calcSat_with_memo(test_applied):

    total_sat = 0
    for d in range(1,D+1):
        lastDay.append(list(lastDay[d-1]))
        sat = 0
        tst = test_applied[d] - 1
        lastDay[d][tst] = d
        sat += SL[d][tst]
        for itst in range(NTEST):
            sat -= C[itst] * (d-lastDay[d][itst])
        satList.append(sat)
        total_sat += sat

    return total_sat

def recalcSat_with_memo(total_sat_before, tday, t_from, t_to, test_applied):

    d_total_sat = 0

    lastDay[tday][t_from -1]=lastDay[tday-1][t_from -1]
    d_sat=0
    d_sat += (SL[tday][t_to -1]-SL[tday][t_from -1])
    d_sat += C[t_to -1]*(tday - lastDay[tday][t_to -1])
    d_sat -= C[t_from -1]*(tday - lastDay[tday][t_from -1])

    lastDay[tday][t_to -1]=tday

    satList[tday]+= d_sat
    d_total_sat  += d_sat

    old_last = tday
    new_last = lastDay[tday][t_from -1]
    for d in range(tday+1,D+1):
        if test_applied[d] == t_from :
            break
        d_sat = C[t_from -1]*(- old_last + new_last)
        lastDay[d][t_from -1] = new_last
        satList[d]+= d_sat
        d_total_sat += d_sat

    old_last = lastDay[tday-1][t_to -1]
    new_last = tday
    for d in range(tday+1,D+1):
        if test_applied[d] == t_to :
            break
        d_sat = C[t_to -1]*(- old_last + new_last)
        lastDay[d][t_to -1] = new_last
        satList[d]+= d_sat
        d_total_sat += d_sat
            
    return d_total_sat





sat = calcSat_with_memo(tests)




M=int(input())

ans = list()

for m in range(M):
    d, new_tst = list(map(int, input().split()))

    d_sat = recalcSat_with_memo(sat, d, tests[d], new_tst, tests)

    tests[d] = new_tst
    sat += d_sat
    ans.append(sat)

for m in range(M):
    print(ans[m])

Solution (Python):
import sys

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  

D = I()
c = [0] + LI()
s = [0] + [[0] + LI() for i in range(D)]
t = [0] + [I() for i in range(D)]
M = I()
dq = [LI() for i in range(M)]

last = [[0]*27 for i in range(D+1)]
manzokudo = 0

for i in range(1,D+1):
    for j in range(1,27):
        if j != t[i]:
            last[i][j] = last[i-1][j]
        else:
            last[i][t[i]] = i
    manzokudo += s[i][t[i]]
    r = 0
    for j in range(1,27):
        r += c[j]*(i-last[i][j])
    manzokudo -= r

for i in range(M):
    d,q = dq[i]
    t0 = t[d]
    manzokudo += s[d][q] - s[d][t0]
    for j in range(d,D+1):
        if j == d:
            last[d][t0] = last[d-1][t0]
            manzokudo -= c[t0] * (d - last[d][t0])
            last[d][q] = d
            manzokudo += c[q] * (d - last[d-1][q])
        else:
            if last[j][t0] == d:
                last[j][t0] = last[d-1][t0]
                manzokudo -= c[t0] * (d - last[d][t0])
            if last[j][q] == last[d-1][q]:
                last[j][q] = d
                manzokudo += c[q] * (d - last[d-1][q])
    t[d] = q
    print(manzokudo)

Solution (Python):
import sys
input=sys.stdin.readline
D=int(input())
c=list(map(int,input().split()))
s=[]
for i in range(D):
    sub=list(map(int,input().split()))
    s.append(sub)
t=[]
for i in range(D):
    t.append(int(input()))

h=0
last=[-1]*26

for i in range(D):
    h+=s[i][t[i]-1]
    last[t[i]-1]=i
    for j in range(26):
        h-=c[j]*(i-last[j])

m=int(input())
for _ in range(m):
    d,q=map(int,input().split())
    h+=s[d-1][q-1]-s[d-1][t[d-1]-1]
    o=t[d-1]
    t[d-1]=q

    pre=1
    for i in range(d-2,-1,-1):
        if t[i]==o:
            break
        pre+=1
    post=1
    for j in range(d,D):
        if t[j]==o:
            break
        post+=1
    h-=c[o-1]*pre*post

    pre = 1
    for i in range(d - 2, -1, -1):
        if t[i] == q:
            break
        pre += 1
    post = 1
    for j in range(d, D):
        if t[j] == q:
            break
        post += 1
    h += c[q - 1] * pre * post

    print(h)

Solution (Python):
def f(a,d,T):
    try:
        return T[d:].index(a)+d
    except ValueError:
        return len(T)

from random import randint
A=26

D=int(input())

C=[0]+list(map(int,input().split())) 
S=[0]*(D+1) 

for i in range(1,D+1):
    S[i]=[0]+list(map(int,input().split()))

T=[0]
for i in range(D):
    T.append(int(input()))

L=[[0]*(A+1) for _ in range(D+1)]

for x in range(1,D+1):
    t=T[x]
    for j in range(1,A+1):
        if t!=j:
            L[x][j]=L[x-1][j]+1
        else:
            L[x][j]=0
            
X=0
for d in range(1,D+1):
    X+=S[d][T[d]]    
    for j in range(1,A+1):
        X-=C[j]*L[d][j]

M=int(input())
for _ in range(M):
    d,q=map(int,input().split())
    p=T[d]

    a=f(p,d+1,T)
    b=f(q,d+1,T)
    
    Y=0
    h=L[d-1][p]
    for i in range(d,a):
        h+=1
        Y+=h-L[i][p]
        L[i][p]=h
        
    m=0
    Z=0
    for j in range(d,b):
        Z-=m-L[j][q]
        L[j][q]=m
        m+=1

    T[d]=q
    X+=(S[d][q]-S[d][p])+Z*C[q]-Y*C[p]
    print(X)

Solution (Python):
import os
import sys

import numpy as np


def solve(inp):
    def bitree_sum(bit, t, i):
        s = 0
        while i > 0:
            s += bit[t, i]
            i ^= i & -i
        return s

    def bitree_add(bit, n, t, i, x):
        while i <= n:
            bit[t, i] += x
            i += i & -i

    def bitree_lower_bound(bit, n, d, t, x):
        sum_ = 0
        pos = 0
        for i in range(d, -1, -1):
            k = pos + (1 << i)
            if k <= n and sum_ + bit[t, k] < x:
                sum_ += bit[t, k]
                pos += 1 << i
        return pos + 1

    def initial_score(d, ccc, sss, ttt):
        bit_n = d + 3
        bit = np.zeros((26, bit_n), dtype=np.int64)
        INF = 10 ** 18
        for t in range(26):
            bitree_add(bit, bit_n, t, bit_n - 1, INF)

        last = np.full(26, -1, dtype=np.int64)
        score = 0

        for i in range(d):
            t = ttt[i]
            score += sss[i, t]
            for u in range(26):
                if u == t:
                    continue
                score -= ccc[u] * (i - last[u])
            last[t] = i
            bitree_add(bit, bit_n, t, i + 2, 1)

        return bit, score

    def update_score(bit, bit_n, bit_d, ccc, sss, ttt, d, q):
        diff = 0
        t = ttt[d]
        bitree_add(bit, bit_n, t, d + 2, -1)
        k = bitree_sum(bit, t, d + 1)
        c = bitree_lower_bound(bit, bit_n, bit_d, t, k) - 2
        e = bitree_lower_bound(bit, bit_n, bit_d, t, k + 1) - 2
        b = ccc[t]
        diff -= b * (d - c) * (e - d)
        diff -= sss[d, t]

        k = bitree_sum(bit, q, d + 2)
        c = bitree_lower_bound(bit, bit_n, bit_d, q, k) - 2
        e = bitree_lower_bound(bit, bit_n, bit_d, q, k + 1) - 2
        bitree_add(bit, bit_n, q, d + 2, 1)
        b = ccc[q]
        diff += b * (d - c) * (e - d)
        diff += sss[d, q]

        return diff

    d = inp[0]
    ccc = inp[1:27]
    sss = np.zeros((d, 26), dtype=np.int64)
    for r in range(d):
        sss[r] = inp[27 + r * 26:27 + (r + 1) * 26]
    ttt = inp[27 + d * 26:27 + d * 27] - 1
    m = inp[27 + d * 27]
    ddd = inp[28 + d * 27::2] - 1
    qqq = inp[29 + d * 27::2] - 1

    bit, score = initial_score(d, ccc, sss, ttt)
    bit_n = d + 2
    bit_d = int(np.log2(bit_n))

    buf = np.zeros(m, dtype=np.int64)

    for i in range(m):
        diff = update_score(bit, bit_n, bit_d, ccc, sss, ttt, ddd[i], qqq[i])
        ttt[ddd[i]] = qqq[i]
        score += diff
        buf[i] = score

    return buf


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8[:],)')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8[:],)', cache=True)(solve)
    print('compiled', file=sys.stderr)

inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
ans = solve(inp)
print('\n'.join(map(str, ans)))

Solution (Python):
from sys import stdin
def main():
    
    readline=stdin.readline
    D=int(readline())
    c=list(map(int,readline().split()))
    s=[list(map(int,readline().split())) for _ in range(D)]
    t=[int(readline()) for _ in range(D)]
    M=int(readline())
    d=[0]*M
    q=[0]*M
    for i in range(M):
        d[i],q[i]=map(int,readline().split())

    kaisai_all=[[0]*26 for _ in range(D)]
    kaisai=[0]*26
    manzokudo=0
    for i in range(D):
        manzokudo+=s[i][t[i]-1]
        kaisai[t[i]-1]=i+1
        if i!=0:
            kaisai_all[i]=kaisai_all[i-1][:]
        kaisai_all[i][t[i]-1]=i+1
        for j in range(26):
            manzokudo-=c[j]*(i+1-kaisai[j])
    
    
    for i in range(M):
        day=d[i]-1
        before_contest_type=t[day]-1
        after_contest_type=q[i]-1
        manzokudo-=s[day][before_contest_type]
        manzokudo+=s[day][after_contest_type]
        t[day]=q[i]

        if day==0:
            tmp=0
        else:
            tmp=kaisai_all[day-1][before_contest_type]
        j=day
        while 0<=j<D and kaisai_all[j][before_contest_type]==day+1:
            kaisai_all[j][before_contest_type]=tmp
            manzokudo-=c[before_contest_type]*(day+1-tmp)
            j+=1
        
        if day==0:
            tmp=0
        else:
            tmp=kaisai_all[day-1][after_contest_type]
        j=day
        while 0<=j<D and kaisai_all[j][after_contest_type]==tmp:
            kaisai_all[j][after_contest_type]=day+1
            manzokudo+=c[after_contest_type]*(day+1-tmp)
            j+=1
        print(manzokudo)

if __name__=="__main__":
    main()

Solution (Python):
D = int(input())
c = [int(i) for i in input().split()]
s = []
for _ in range(D):
    s.append([int(i) for i in input().split()])
score = 0
days = [[0]*26 for i in range(D+1)]
T = []
for k in range(D):
    t = int(input())-1
    T.append(t)
    for i in range(26):
        if i == t:
            days[k+1][i] = 0
        else:
            days[k+1][i] = days[k][i]+1
    score += s[k][t]
    for i in range(26):
        score -= days[k+1][i]*c[i]
M = int(input())
for _ in range(M):
    d,q = [int(i)-1 for i in input().split()]
    diff = s[d][q] - s[d][T[d]]
    i = d+1
    for k in range(d+1,D):
        if T[k] == q:
            i = k
            break
    else:
        i = D
    j = d+1
    for k in range(d+1,D):
        if T[k] == T[d]:
            j = k
            break
    else:
        j = D
    diff -= c[T[d]]*(days[d][T[d]]+1)*(j-d) - c[q]*days[d+1][q]*(i-d)
    score += diff
    L = days[d+1][q]
    for k in range(d+1,i+1):
        days[k][q]  -= L
    L = days[d][T[d]]+1
    for k in range(d+1,j+1):
        days[k][T[d]] += L
    T[d] = q
    print(score)

Solution (Python):


import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())
from bisect import bisect

def resolve():
    it = map(int, sys.stdin.read().split())
    D = next(it)
    C = [next(it) for i in range(26)]
    S = [[next(it) for i in range(26)] for i in range(D)]
    L = [[-1] for i in range(26)]
    T = [-1] * D

    score = 0
    for i in range(D):
        ti = next(it)-1
        score += S[i][ti]
        L[ti].append(i)
        T[i] = ti
        for ci, la in zip(C, L):
            score -= ci * (i-la[-1])

    N = next(it)
    for i in range(N):
        di, qi = next(it)-1, next(it)-1

        t0 = T[di]
        score += S[di][qi]-S[di][t0]
        T[di] = qi

        li = L[t0]
        ii = li.index(di)
        la = D if len(li)-1 == ii else li[ii+1]
        score -= C[t0] * (di-li[ii-1])*(la-di)
        li.remove(di)

        li = L[qi]
        ii = bisect(li, di)
        li.insert(ii, di)
        la = D if len(li)-1 == ii else li[ii+1]
        score += C[qi] * (di-li[ii-1])*(la-di)

        print(score)


if __name__ == "__main__":
    resolve()

Solution (Python):
from collections import defaultdict
D = int(input())
C = list(map(int,input().split())) 
S = [] 
for i in range(D): 
    temp = list(map(int,input().split()))
    S.append(temp)
T = []
dic = defaultdict(list)
for i in range(D):
    temp = int(input())
    temp-=1 
    T.append(temp)
    dic[temp].append(i)
for i in range(len(dic)):
    dic[i].sort()
M = int(input())
DQ = []
for i in range(M):
    d,q = map(int,input().split())
    DQ.append((d,q))


def cycle(T):
    manzoku = 0
    since = [0 for _ in range(26)]
    for i in range(26):
        since[i] += C[i]
    for i in range(D):
        contest = T[i] 
        manzoku += S[i][contest]
        for j in range(26):
            if j != contest:
                manzoku -= since[j]
        
        for j in range(26):
            if j != contest:
                since[j] += C[j]
            else:
                since[j] = C[j]
    return manzoku
score = cycle(T)

for i in range(M):
    
    d,q = DQ[i] 
    d-=1;q-=1 
    old = T[d]
    try:
        oscore = nscore*1
    except:
        oscore= score*1
    dic[old].remove(d)
    T[d] = q
    if old == q:
        nscore = oscore
    else:
        impact = S[d][q]-S[d][old] 
        
        if not dic[q]:
            impact += C[q]*(D-d)*(d+1)
        else:
            for j in range(len(dic[q])):
                if d < dic[q][0]:
                    impact += C[q]*(d+1)*(dic[q][0]-d)
                    break
                elif d > dic[q][-1]:
                    impact += C[q]*(D-d)*(d-dic[q][-1])
                    break
                else:
                    if dic[q][j] < d and d < dic[q][j+1]:
                        impact += C[q]*(d-dic[q][j])*(dic[q][j+1]-d)
                        break
        dic[q].append(d)
        dic[q].sort()
        if not dic[old]:
            impact -= C[old]*(D-d)*(d+1)
        else:
            for j in range(len(dic[old])):
                if d < dic[old][0]:
                    impact -= C[old]*(d+1)*(dic[old][0]-d)
                    break
                elif d > dic[old][-1]:
                    impact -= C[old]*(D-d)*(d-dic[old][-1])
                    break
                else:
                    if dic[old][j] < d and d < dic[old][j+1]:
                        impact -= C[old]*(d-dic[old][j])*(dic[old][j+1]-d)
                        break
        nscore = oscore+impact
    
    print(nscore)

Solution (Python):
D = int(input())
C = list(map(int, input().split()))
S = [list(map(int, input().split())) for _ in range(D)]
from bisect import *
scores = []
last = [-1]*26
score = 0
points = [0]*26
dates = [[-1] for _ in range(26)]
T = [int(input())-1 for _ in range(D)]
for d in range(D):
    dates[T[d]].append(d)
    score += S[d][T[d]]
    last[T[d]] = d
    for j in range(26):
        score -= C[j]*(d-last[j])
for i in range(26):
  dates[i].append(D)
M = int(input())
for _ in range(M):
  d,after = map(int, input().split())
  d -= 1
  after -= 1
  before = T[d]
  T[d] = after
  insort_right(dates[after],d)
  score += S[d][after]-S[d][before]
  ind_bef = bisect_right(dates[before],d)-1
  score -= C[before]*(dates[before][ind_bef]-dates[before][ind_bef-1])*(dates[before][ind_bef+1]-dates[before][ind_bef])
  ind_aft = bisect_right(dates[after],d)-1
  score += C[after]*(dates[after][ind_aft]-dates[after][ind_aft-1])*(dates[after][ind_aft+1]-dates[after][ind_aft])
  dates[before].pop(ind_bef)
  scores.append(score)
print(*scores, sep='\n')

Solution (Python):
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    from bisect import bisect_left,bisect_right
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10

    D = II()
    C = LMIIS()
    S = []
    for i in range(D):
        S.append(LMIIS())
    T = [0]*D
    for i in range(D):
        T[i] = II()
    

    M = II()
    Q = []
    for i in range(M):
        Q.append(LMIIS())
    satisfaction = 0
    last_helds = []
    for i in range(26):
        last_helds.append([-1])

    satisfactions = [0] * D
    for i,t in enumerate(T):
        last_helds[t-1].append(i)
        for j in range(26):
            satisfaction -= C[j] * (i-last_helds[j][-1])
        satisfaction += S[i][t-1]
    
    for i in range(26):
        last_helds[i].append(D)

    for d,q in Q:
        old = T[d-1]

        satisfaction -= S[d-1][old-1]
        satisfaction += S[d-1][q-1]

        old_idx = bisect_left(last_helds[old-1],d-1)
        dbg(last_helds[old-1],d-1,old_idx)
        x = last_helds[old-1][old_idx - 1]
        y = last_helds[old-1][old_idx + 1]
        dbg('old x,y',d-1,x,y,(1+(y-1-(d-1)))*(y-(d-1)-1)//2,(1+(d-1)-x-1)*((d-1)-x-1)//2,(1+ y-x-1)*(y-x-1)//2)
        satisfaction += C[old-1] * ((1+(y-1-(d-1)))*(y-(d-1)-1)//2  + (1+(d-1)-x-1)*((d-1)-x-1)//2)
        satisfaction -= C[old-1] * ((1+ y-x-1)*(y-x-1)//2)
        
        new_idx = bisect_left(last_helds[q-1],d-1)
        dbg(last_helds[q-1],d-1,new_idx)
        x = last_helds[q-1][new_idx-1]
        y = last_helds[q-1][new_idx]
        satisfaction += C[q-1]*((1+y-x-1)*(y-x-1)//2)
        satisfaction -= C[q-1]*((1+(d-1)-x-1)*((d-1)-x-1)//2+(1+y-(d-1)-1)*(y-(d-1)-1)//2)
        

        last_helds[old-1].pop(old_idx)
        dbg('insert')
        dbg(last_helds[q-1])
        last_helds[q-1].insert(new_idx,d-1)
        dbg(last_helds[q-1])
        T[d-1] = q

        print(satisfaction)



    
main()

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

ans = 0
for i in range(D):
    op = t[i]-1
    ans += s[i][op]
    last[op].append(i)
    for j in range(26):
        ans -= c[j]*(i-last[j][-1])
    
from bisect import *
import random
m = int(input())
def suminc(a,b):
    return b*(b-1)//2-a*(a-1)//2
while m:
    m-=1
    update = 0
    d,q = map(int, input().split())
    
    
    d-=1
    q-=1
    oq = t[d]-1
    update += s[d][q]-s[d][oq]
    idx = bisect_left(last[oq],d)
    if idx == len(last[oq])-1:
        cnt = D - last[oq][idx]
    else:
        cnt = last[oq][idx+1] - last[oq][idx]
    update += c[oq]*suminc(0,cnt)
    cntprv = last[oq][idx] - last[oq][idx-1]
    update -= c[oq]*suminc(cntprv,cntprv+cnt)

    idx2 = bisect_left(last[q],d)-1
    if idx2 == len(last[q])-1:
        cnt = D - d
    else:
        cnt = last[q][idx2+1] - d
    if idx2 == len(last[q])-1:
        cntprv = D - last[q][idx2] - cnt
    else:
        cntprv = last[q][idx2+1] - last[q][idx2] - cnt
    update += c[q]*suminc(cntprv,cntprv+cnt)
    update -= c[q]*suminc(0,cnt)

    ans += update
    del last[oq][idx]
    last[q].insert(idx2+1,d)
    print(ans)
    t[d] = q+1