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.



Sample input:
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:
72882
56634
38425
27930
42884

Submission status: Runtime Error

Solution code:
import os
import sys

import numpy as np


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 + 2
    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 + 1, 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 + 1, -1)
    k = bitree_sum(bit, t, d + 1)
    c = bitree_lower_bound(bit, bit_n, bit_d, t, k) - 1
    e = bitree_lower_bound(bit, bit_n, bit_d, t, k + 1) - 1
    b = ccc[t]
    diff -= b * (d - c + 1) * (e - d)
    diff -= sss[d, t]

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

    ttt[d] = q

    return diff


def solve(inp):
    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])
        score += diff
        buf[i] = score

    return buf


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

    cc = CC('my_module')
    cc.export('bitree_sum', '(i8[:,:],i8,i8)')(bitree_sum)
    cc.export('bitree_add', '(i8[:,:],i8,i8,i8,i8)')(bitree_add)
    cc.export('bitree_lower_bound', '(i8[:,:],i8,i8,i8,i8)')(bitree_lower_bound)
    cc.export('initial_score', '(i8,i8[:],i8[:,:],i8[:])')(initial_score)
    cc.export('update_score', '(i8[:,:],i8,i8,i8[:],i8[:,:],i8[:],i8,i8)')(update_score)
    cc.export('solve', '(i8[:],)')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import bitree_sum, bitree_add, bitree_lower_bound, initial_score, update_socer, solve
else:
    from numba import njit

    bitree_sum = njit('(i8[:,:],i8,i8)', cache=True)(bitree_sum)
    bitree_add = njit('(i8[:,:],i8,i8,i8,i8)', cache=True)(bitree_add)
    bitree_lower_bound = njit('(i8[:,:],i8,i8,i8,i8)', cache=True)(bitree_lower_bound)
    initial_score = njit('(i8,i8[:],i8[:,:],i8[:])', cache=True)(initial_score)
    update_score = njit('(i8[:,:],i8,i8,i8[:],i8[:,:],i8[:],i8,i8)', cache=True)(update_score)
    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)))

Submission status: Runtime Error

Solution code:
from bisect import bisect_right, bisect_left
# instead of AVLTree
class BITbisect():
    def __init__(self, InputProbNumbers):
        # 座圧
        self.ind_to_co = [-10**18]
        self.co_to_ind = {}
        for ind, num in enumerate(InputProbNumbers):
            self.ind_to_co.append(num)
            self.co_to_ind[num] = ind+1
        self.max = len(self.co_to_ind)
        self.data = [0]*(self.max+1)
    
    def __str__(self):
        retList = []
        for i in range(1, self.max+1):
            x = self.ind_to_co[i]
            if self.count(x):
                c = self.count(x)
                for _ in range(c):
                    retList.append(x)
        return "[" + ", ".join([str(a) for a in retList]) + "]"
    
    def __getitem__(self, key):
        key += 1
        s = 0
        ind = 0
        l = self.max.bit_length()
        for i in reversed(range(l)):
            if ind + (1<<i) <= self.max:
                if s + self.data[ind+(1<<i)] < key:
                    s += self.data[ind+(1<<i)]
                    ind += (1<<i)
        if ind == self.max or key < 0:
            raise IndexError("BIT index out of range")
        return self.ind_to_co[ind+1]
    
    def __len__(self):
        return self._query_sum(self.max)
    
    def __contains__(self, num):
        if not num in self.co_to_ind:
            return False
        return self.count(num) > 0
    
    # 0からiまでの区間和
    # 左に進んでいく
    def _query_sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    # i番目の要素にxを足す
    # 上に登っていく
    def _add(self, i, x):
        while i <= self.max:
            self.data[i] += x
            i += i & -i
    
    # 値xを挿入
    def push(self, x):
        if not x in self.co_to_ind:
            raise KeyError("The pushing number didnt initialized")
        self._add(self.co_to_ind[x], 1)
            
    # 値xを削除
    def delete(self, x):
        if not x in self.co_to_ind:
            raise KeyError("The deleting number didnt initialized")
        if self.count(x) <= 0:
            raise ValueError("The deleting number doesnt exist")
        self._add(self.co_to_ind[x], -1)

    # 要素xの個数
    def count(self, x):
        return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1)
    
    # 値xを超える最低ind
    def bisect_right(self, x):
        if x in self.co_to_ind:
            i = self.co_to_ind[x]
        else:
            i = bisect_right(self.ind_to_co, x) - 1
        return self._query_sum(i)

    # 値xを下回る最低ind
    def bisect_left(self, x):
        if x in self.co_to_ind:
            i = self.co_to_ind[x]
        else:
            i = bisect_left(self.ind_to_co, x)
        if i == 1:
            return 0
        return self._query_sum(i-1)

import sys
input = sys.stdin.readline

Days = int(input())
C = list(map(int, input().split())) # 満足度低下
Ss = [list(map(int, input().split())) for _ in range(Days)]
# Ss[d][i]: d日目にiを開催したときの満足度
T = [int(input()) for _ in range(Days)] # 開催するコンテスト
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]

INF = 10**18

def outputToScore(T):
    last = [0]*26
    used = [BITbisect(list(range(Days+1))) for _ in range(26)]
    satisfied = 0
    for d, t in enumerate(T):
        t -= 1; d += 1
        satisfied += Ss[d-1][t]
        used[t].push(d)
        last[t] = d
        for i, c in enumerate(C):
            satisfied -= c*(d-last[i])
        # print(satisfied)
    return satisfied, used

Satisfied, Used = outputToScore(T)
for d, aft in Query:
    aft -= 1
    bef = T[d-1]-1
    deltaSatis = Ss[d-1][aft] - Ss[d-1][bef]
    # d日目のコンテストをbefからaftに変える
    befind = Used[bef].bisect_left(d)
    aftind = Used[aft].bisect_left(d)
    #print(d)
    #print(Used[bef], bef)
    #print(Used[aft], aft)
    # bi-1 -> bi -> bi+1 を bi-1 -> bi+1
    befday0 = 0
    befday2 = Days+1
    if befind > 0:
        befday0 = Used[bef][befind-1]
    if befind < len(Used[bef])-1:
        befday2 = Used[bef][befind+1]
    befd01 = d - befday0
    befd12 = befday2 - d
    befd02 = befday2-befday0
    deltaSatis -= C[bef]*(befd02*(befd02-1)//2) - C[bef]*(befd01*(befd01-1)//2 + befd12*(befd12-1)//2)

    # ai -> ai+1 を ai -> (insert) -> ai+1
    if len(Used[aft]) > 0:
        aftday0 = 0
        aftday2 = Used[aft][aftind]
        if aftind > 0:
            aftday0 = Used[aft][aftind-1]
        aftd01 = d - aftday0
        aftd12 = aftday2 - d
        aftd02 = aftd01 + aftd12
        deltaSatis += C[aft]*(aftd02*(aftd02-1)//2) - C[aft]*(aftd01*(aftd01-1)//2 + aftd12*(aftd12-1)//2)
    else:
        d01 = d
        d12 = Days+1 - d
        deltaSatis += C[aft] * Days*(Days+1)//2 - C[aft]*(d01*(d01-1)//2 + d12*(d12-1)//2)

    Used[bef].delete(d)
    Used[aft].push(d)
    T[d-1] = aft+1
    Satisfied += deltaSatis
    print(Satisfied)

Submission status: Runtime Error

Solution code:
import sys


def read():
    return sys.stdin.readline().rstrip()


def main():
    d = int(read())
    c = [int(i) for i in read().split()]
    s = [[int(i) for i in read().split()] for _ in range(d)]
    t = [int(read()) - 1 for _ in range(d)]
    m = int(read())
    query = [[int(i) - 1 for i in read().split()] for _ in range(m)]
    score = [0] * 26
    last = [[0] * 26 for _ in range(d)]
    for i in range(d):
        score[i] = s[i][t[i]]
        if i > 0:
            last[i] = last[i - 1].copy()
        last[i][t[i]] = i + 1
        for j in range(26):
            score[i] -= c[j] * (i + 1 - last[i][j])
    for di, qi in query:
        if di == 0:
            last[di][t[di]] = 0
        else:
            last[di][t[di]] = last[di - 1][t[di]]
        last[di][qi] = di + 1
        t[di] = qi
        for i in range(di, d):
            score[i] = s[i][t[i]]
            if i > 0:
                last[i] = last[i - 1].copy()
            last[i][t[i]] = i + 1
            for j in range(26):
                score[i] -= c[j] * (i + 1 - last[i][j])
        print(sum(score))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
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)]
m = int(input())
q = [list(map(int, input().split())) for i in range(d)]
mem = [0 for i in range(26)]
v = 0
ol = t
for b in range(m):
    ol[q[b][0]-1] = q[b][1]
    v = 0
    for a in range(d):
        v += s[a][ol[a]-1]
        mem[ol[a]-1] = a+1
        for i in range(26):
            v -= c[i]*(a+1 - mem[i])
    print(v)

Submission status: Runtime Error

Solution code:
import bisect

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)]#コンテストの開催
Last = [[-1] for _ in range(26)]

ans = 0

for i in range(D):
    t = T[i]
    ans += S[i][t-1]
    Last[t-1].append(i) 
    for k in range(26):
        ans -= C[k] * (i - max(Last[k]))
    #print(ans)

M = int(input())

for i in range(M):
    d, q = map(int,input().split())
    d -= 1
    q -= 1
    old = T[d]
    T[d] = q 
    
    tmp = ans
    tmp += S[d][q] - S[d][old]
    
    if max(Last[q]) < d:
        tmp += C[q] * (D - d - 1)
    else:
        q_ind = bisect.bisect_left(Last[q], d)
        tmp += C[q] * (Last[q][q_ind-1] - d)

    if max(Last[old]) < d:
        tmp -= C[old] * (D - d - 1)
    else:
        old_ind = bisect.bisect_left(Last[old], d)
        tmp -= C[old] * (Last[old][old_ind-1] - d) 
    
    if tmp <= ans:
        T[d] = old
        continue
    if d in Last[old]:
        Last[old].remove(d)
    bisect.insort_left(Last[q], d)
    
Last = [[-1] for _ in range(26)]
ans = 0
for i in range(D):
    t = T[i]
    ans += S[i][t-1]
    Last[t-1].append(i) 
    for k in range(26):
        ans -= C[k] * (i - max(Last[k]))
    print(ans)

Submission status: Runtime Error

Solution code:
#create date: 2020-06-28 21:05

import sys
stdin = sys.stdin
from numba import njit

def ns(): return stdin.readline().rstrip()
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))


def calc(t, s, c, d):
        period = [0]*26
        last_day = [0]*26
        v = 0
        for day in range(1, d+1):
            last_day[t[day-1]] = day
        
            v += s[day-1][t[day-1]]
            for ci, last_day_i in zip(c, last_day):
                v -= ci * (day - last_day_i)
        return print(int(v))

def main():
    d = ni()
    c = na()
    s = list()
    for i in range(d):
        a = na()
        s.append(a)
    t = list()
    for i in range(d):
        t.append(ni()-1)

    m = ni()
    for i in range(m):
        di, qi = na()
        t[di-1] = qi-1
        calc(t, s, c, d)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
D = int(input())
c_list = [int(i) for i in input().split()]
s_list = []
t_list = []
for _ in range(D):
    s = [int(i) for i in input().split()]
    s_list.append(s)
for _ in range(D):
    t_list.append(int(input()))
happy = 0
recent = [0 for _ in range(26)]
for i in range(D):
    happy += s_list[i][t_list[i] - 1]
    recent[t_list[i] - 1] = i + 1
    for j, s in enumerate(s_list[i]):
        happy -= c_list[j] * (i + 1 - recent[j])
M = int(input())
for i in range(M):
    d, q = map(int, input().split())
    d -= 1
    happy += s_list[d][q - 1] - s_list[d][t_list[d] - 1]    
    for dd in range(d, D if recent[q - 1] <= d else recent[q - 1]):
        happy += c_list[q - 1] - c_list[d - 1]
    print(happy)

Submission status: Runtime Error

Solution code:
import copy
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)]
m = int(input())
q = [list(map(int, input().split())) for i in range(d)]
mem = [0 for i in range(26)]
v = 0
su = sum(c)
ol = t
for b in range(m):
    for j in range(26):
        mem[j] = 0
    #ol = copy.deepcopy(t)
    ol[q[b][0]-1] = q[b][1]
    v = 0
    for a in range(d):
        v += s[a][ol[a]-1]
        mem[ol[a]-1] = a+1
        for i in range(26):
            v -= c[i]*(a+1 - mem[i])
    print(v)

Submission status: Runtime Error

Solution code:
#create date: 2020-06-28 21:05

import sys
stdin = sys.stdin

def ns(): return stdin.readline().rstrip()
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))


def calc(t, s, c, d):
        period = np.zeros(26)
        last_day = np.zeros(26)
        v = 0
        for day in range(1, d+1):
            last_day[t[day-1]] = day
        
            v += s[day-1][t[day-1]]
            for ci, last_day_i in zip(c, last_day):
                v -= ci * (day - last_day_i)
        return print(int(v))

def main():
    d = ni()
    c = np.array(na())
    s = list()
    for i in range(d):
        a = na()
        s.append(a)
    t = list()
    for i in range(d):
        t.append(ni()-1)

    
    m = ni()
    for i in range(m):
        di, qi = na()
        t[di-1] = qi-1
        calc(t, s, c, d)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from numba import jit, f8, i8, b1, void
import numpy as np

d = int(input())
cs = list(map(int, input().split()))
sm = [list(map(int, input().split())) for _ in range(d)]

#@njit('i8(i8[:])', cache=True)
@jit('i8(i8[:])')
def total_satisfaction(ts):
    ls = np.zeros(26, dtype=np.int64)
    #ls = [0] * 26
    s = 0
    for i in range(d):
        t = ts[i]
        t -= 1
        s += sm[i][t]
        ls[t] = i + 1

        dis = 0
        for j in range(26):
            dis += cs[j] * ((i+1) - ls[j])
        s -= dis
    return s

ts = [int(input()) for _ in range(d)]
m = int(input())
dqs = [list(map(int, input().split())) for _ in range(m)]
for di, qi in dqs:
    ts[di - 1] = qi
    v = np.array(ts, dtype=np.int64)
    s = total_satisfaction(v)
    print(s)

Submission status: Runtime Error

Solution code:
s=[list(map(int,input().split())) for _ in range(D)]
t=[int(input()) for _ in range(D)]
d=int(input())
q=[list(map(int,input().split())) for _ in range(d)]

"""
day_last=[0]*26

def minus(day):
    return sum([c[i]*(day+1-day_last[i]) for i in range(26)])

def plus(day,contest_number):
    return s[day][contest_number-1]
"""
def solve(t):
    
    def minus(day):
        return sum([c[i]*(day+1-day_last[i]) for i in range(26)])

    def plus(day,contest_number):
        return s[day][contest_number-1]
    
    day_last=[0]*26
    points=0
    
    for day,contest_number in enumerate(t):
        day_last[contest_number-1]=day+1
        points=points+plus(day,contest_number)-minus(day)
        #print(points)
    
    return points

for i in q:
    t[i[0]-1]=i[1]
    print(solve(t))

Submission status: Runtime Error

Solution code:
import copy
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)]
m = int(input())
q = [list(map(int, input().split())) for i in range(d)]
mem = [0 for i in range(26)]
ans = []
v = 0
su = sum(c)
for a in range(d):
    v += s[a][t[a]-1]
    mem[t[a]-1] = a+1
    for i in range(26):
        v -= c[i]*(a+1 - mem[i])
    #print(v)
    ans.append(v)
ol = t
for b in range(m):
    mem = [0 for i in range(26)]
    #ol = copy.deepcopy(t)
    ol[q[b][0]-1] = q[b][1]
    v = 0
    for a in range(d):
        v += s[a][ol[a]-1]
        mem[ol[a]-1] = a+1
        for i in range(26):
            v -= c[i]*(a+1 - mem[i])
    print(v)

Submission status: Runtime Error

Solution code:
#TLE
import numpy as np
#基本入力
D = int(input())
c =list(map(int,input().split()))
s = []
for i in range(D):
        s.append(list(map(int,input().split())))
t = []
for i in range(D):
    t.append(int(input()))
M = int(input())
dq = []
for i in range(M):
    dq.append(list(map(int,input().split())))
        
#基本入力完了
#得点計算
for quri in range(M):
    c = np.array(c)
    last_day = np.array([0]*26)
    day_pulse = np.array([1]*26)
    s = np.array(s)
    t = np.array(t)
    t[dq[quri][0]-1] = dq[quri][1]
    manzoku = 0
    for day in range(1,D+1):
        contest_number = t[day-1] #開催するコンテスト種類
        manzoku += s[day-1,contest_number-1] #開催したコンテストによる満足度上昇
        last_day += day_pulse #経過日数の計算
        last_day[contest_number -1 ] = 0 #開催したコンテスト種類の経過日数を0に
        manzoku -= sum(c*last_day) #開催していないコンテストによる満足度の減少
    print(manzoku)

Submission status: Runtime Error

Solution code:
d=int(input())
c=list(map(int,input().split()))
num=[]
for i in range(d):
    num.append(list(map(int,input().split())))
t=[]
for i in range(d):
    t.append(int(input()))
m=int(input())
ans1=[]
for i in range(m):
    ans=0
    num2=[0]*26
    a,q=map(int,input().split())
    t[a-1]=q
    for j in range(1,d+1):
        num2[t[j-1]-1]=j
        ans+=num[j-1][t[j-1]-1]
        for k in range(26):
            ans-=((j-num2[k])*c[k])
    ans1.append(ans)
for i in range(d):
    print(ans1[i])

Submission status: Runtime Error

Solution code:
from collections import deque
d = int(input())
C = list(map(int,input().split()))
S = [list(map(int,input().split())) for i in range(d)]
T = [int(input())-1 for i in range(d)]
M = int(input())
Q = deque([list(map(int,input().split())) for i in range(d)])

def incrase(day,probrem_id,last_li,score):
    score+=S[day][problem_id]
    last_li[problem_id]=day+1
    return score,last_li
    
def decrease(day,last_li,score):
    for i in range(26):
        score-=C[i]*(day+1-(0 if last_li[i]==-1 else last_li[i]))
    return score

while Q:
    di,qi = Q.popleft()
    T[di-1] = qi-1
    
    score = 0
    day = 0
    last_li = [-1]*26

    for i in range(d):
        problem_id = T[i]
        score,last_li = incrase(i,problem_id,last_li,score)
        score = decrease(i,last_li,score)
    print(score)

Submission status: Runtime Error

Solution code:
import numpy as np
d=int(input())
c=[0]+[int(j)for j in input().split()]
s=[[0]+[int(j)for j in input().split()]for i in range(d)]
t=[int(input())for i in range(d)]
m=int(input())
dq=[[int(j)for j in input().split()]for i in range(m)]
for p,q in dq:
    l=[0]*27
    ans=0
    t[p-1]=q
    for i,j in enumerate(t,1):
        ans+=s[i-1][j]
        l[j]=i
        for k in range(1,27):
            ans-=(i-l[k])*c[k]
    print(ans)

Submission status: Runtime Error

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    from bisect import bisect_left
    input = sys.stdin.readline

    D = int(input())
    C = list(map(int, input().split()))
    S = []
    for _ in range(D):
        S.append(list(map(int, input().split())))
    ans = 0
    last = [-1] * 26
    days = [[-1] for _ in range(26)]
    T = []
    for d in range(D):
        t = int(input()) - 1
        T.append(t)
        ans += S[d][t]
        last[t] = d
        days[t].append(d)
        for i in range(26):
            ans -= C[i] * (d - last[i])
    for t in range(26):
        days[t].append(D)

    M = int(input())
    for _ in range(M):
        d, q = map(int, input().split())
        d -= 1
        q -= 1
        t = T[d]
        ans += S[d][q]
        ans -= S[d][t]
        i = bisect_left(days[q], d)
        ans += C[q] * (d - days[q][i-1]) * (days[q][i] - d)
        j = bisect_left(days[t], d)
        ans -= C[t] * (d - days[t][i-1]) * (days[t][i+1] - d)
        #print(days[q], days[t])
        T[d] = q
        days[q].append(d)
        days[q].sort()
        days[t].remove(d)
        print(ans)


if __name__ == '__main__':
    main()