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: Time Limit Exceeded

Solution code:
import copy
D=int(input())
ListC = list(map(int, input().split()))
dictC={}
for i in range (1,27):
   dictC[i] = int(0) 
ListS = []
for i in range (D):
   ListS.append(list(map(int, input().split())))
ListT = []
for i in range (D):
   ListT.append(int(input()))
M = int(input())
ListM = []
for i in range (M):
   ListM.append(list(map(int, input().split())))

def calc_figure(list_s, list_t, list_c, dict_c):
  res = 0
  for j in range(D):
    res += list_s[j][list_t[j]-1]
    for i in range(1,27):
      if list_t[j] == i:
        pass
      else:
        res += -1*(j+1-dict_c[i])*list_c[i-1]
    dict_c[list_t[j]] = j+1
  return res

ListT2 = copy.deepcopy(ListT)
for i in range(M):
  for k in range (1,27):
    dictC[k] = int(0) 
  ListT2[ListM[i][0]-1] = ListM[i][1]
  print(calc_figure(ListS, ListT2, ListC, dictC))

Submission status: Time Limit Exceeded

Solution code:
import time
start = time.time()
import random
D = int(input())
*c, = map(int, input().split())
S = []
for _ in [None] * D:
    *s, = map(int, input().split())
    S += s,
INF = float("inf")

def Tread(D):
    return [int(input()) - 1 for i in [None] * D]

def check(T):
    M = 0
    MM = []
    last = [-1] * 26
    for d, t in enumerate(T):
        M += S[d][t] - sum((d - last[i]) * c[i] for i in range(26) if i != t)
        last[t] = d
        # MM += M,
    return M # MM

def C():
    T = Tread(D)
    for i in range(int(input())):
        d, q = map(int, input().split())
        T[d - 1] = q - 1
        print(check(T))
C()

Submission status: Time Limit Exceeded

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())
d0, q = zip(*[list(map(int, input().split())) for i in range(m)])

for i in range(m):
    last = [0]*26
    S = 0
    t[d0[i]-1] = q[i]
    for d in range(1, D+1):
        # last更新
        for j in range(26):
            if j == t[d-1]-1:
                last[j] = d
    
        # plus部分
        S += s[d-1][t[d-1]-1]
    
        # minus部分
        m = 0
        for j in range(26):
            m += c[j] * (d-last[j])
        
        S -= m
        
    print(S)

Submission status: Time Limit Exceeded

Solution code:
def main():
    D = int(input())
    c = list(map(int,input().split()))
    s = []
    for d in range(D):
        s.append(list(map(int,input().split())))
    
    t = []
    for d in range(D):
        t.append(int(input())-1)
    
    M = int(input())
    
    Q = []
    for m in range(M):
        Q.append(list(map(int,input().split())))
    
    last = [0 for i in range(26)]
    
    V = []
    I = []
    v = 0
    
    for d in range(D):
        v += s[d][t[d]]
        last[t[d]] = d+1
        for i in range(26):
            v -= c[i]*(d+1-last[i])
        V.append(v)
        I.append(t[d])
        
    for q in Q:
        last = [0 for i in range(26)]
        v = 0
        t[q[0]-1] = q[1]-1
        for d in range(D):
            v += s[d][t[d]]
            last[t[d]] = d+1
            for i in range(26):
                v -= c[i]*(d+1-last[i])
        print(v)
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import random

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(random.uniform(0,26)))
    t.append(int(input()))
lastds = [0]*26
ans = 0
satisfaction = 0
#initial
for d in range(D):
    lastds[t[d]-1] = d+1
    satisfaction += S[d][t[d]-1]
    for i in range(26):
        satisfaction -= C[i] * (d+1-lastds[i])
#print(satisfaction)
M = int(input())
change = []
for i in range(M):
    change.append(list(map(int,input().split())))
for i in range(M):
    satisfaction = 0
    lastds = [0]*26
    t[change[i][0]-1] = change[i][1] 
    #print(t)
    for d in range(D):
        lastds[t[d]-1] = d+1
        satisfaction += S[d][t[d]-1]
        for i in range(26):
            satisfaction -= C[i] * (d+1-lastds[i])
    print(satisfaction)

Submission status: Time Limit Exceeded

Solution code:
def c_incremental_scoring():
    """B 問題の入力と、追加で「d 日目のコンテストのタイプを q に変更するクエリ」が
    与えられるので、それに基づいて日毎の満足度を計算せよ。
    (A 問題では (大雑把に言って) クエリをうまく与えて満足度を可能な限り高くしていく)"""

    D = int(input())
    Contests = [int(i) for i in input().split()]
    Satisfaction = [[int(i) for i in input().split()] for j in range(D)]
    Contest_type = [int(input()) for _ in range(D)]
    M = int(input())
    Queries = [[int(i) for i in input().split()] for j in range(M)]

    ans = []

    for d, q in Queries:
        Contest_type[d - 1] = q
        current_satisfaction = 0
        last = {i: 0 for i in range(1, 27)}
        for day, t in enumerate(Contest_type, 1):
            current_satisfaction += Satisfaction[day - 1][t - 1]
            last[t] = day

            satisfaction_decreasing = 0
            for i in range(1, 27):
                satisfaction_decreasing += Contests[i - 1] * (day - last[i])
            current_satisfaction -= satisfaction_decreasing
        ans.append(current_satisfaction)
    return '\n'.join(map(str, ans))

print(c_incremental_scoring())

Submission status: Time Limit Exceeded

Solution code:
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())
dq = [list(map(int, input().split())) for _ in range(M)]

def calc(t, D, s):
  last = [0 for _ in range(26)]
  value = 0
  for i in range(D):
    day = i + 1
    value += s[i][t[i]-1]
    last[t[i]-1] = day
    for j in range(26):
      value -= c[j] * (day - last[j])
  return value

for i in range(M):
  t[dq[i][0]-1] = dq[i][1]
  print(calc(t, D, s))

Submission status: Time Limit Exceeded

Solution code:
d = int(input())
C = list(map(int, input().split()))
S = []
for i in range(d):
    S.append(list(map(int, input().split())))
T = [0]
for i in range(d):
    T.append(int(input()))
m = int(input())
D = [0] * m
Q = [0] * m
for i in range(m):
    D[i], Q[i] = map(int, input().split())
"""for i in range(m):
    day, contest = D[i], Q[i] - 1
    T[day] = contest
"""
#print(D, Q)
#print(S)
#print(T)

#最終開催日
Last = [0] * 26

#各Scores
Scores = [0] * 26

def print_score():
    for day in range(1, d+1):
        contest = T[day] - 1
        Last[contest] = day
        Scores[contest] += S[day-1][contest]
        for num in range(26):
            Scores[num] -= C[num] * (day - Last[num])
    print(sum(Scores))

for i in range(m):
    # 最終開催日
    Last = [0] * 26
    # 各Scores
    Scores = [0] * 26

    day, contest = D[i], Q[i]
    T[day] = contest
    print_score()

Submission status: Time Limit Exceeded

Solution code:
import copy

def main():


    d = int(input())
    cList = input().split()

    sList = []

    for idx in range(0, d):
        tempList = input().split()
        sList.append(tempList)

    tList = []

    for idx in range(0, d):
        tList.append(int(input()))

    m = int(input())
    qList = []

    for idx in range(0, m):
        tmpList = [int(x) for x in input().split()]
        qList.append(tmpList)

    val = calcVal(sList, tList, cList, d)

    for qidx in range(0, m):
        temp_tlist = copy.deepcopy(tList)
        temp_tlist[qList[qidx][0] -1] = qList[qidx][1] #日付書き換え

        opposit_val = calcVal(sList, temp_tlist, cList, d)
        #if (opposit_val > val):
        val = opposit_val
        tList = temp_tlist

        print(val)



def calcVal(sList, tList,cList, d):

    count_list = [0] * 26
    val = 0

    for idx in range(0, d):
        val += int(sList[idx][tList[idx] - 1])

        count_list = list(map(lambda x: x + 1, count_list))
        count_list[int(tList[idx]) - 1] = 0

        for wkChar in range(0, 26):
            val -= int(count_list[wkChar]) * int(cList[wkChar])

    return val


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
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)]]

# sat = calcSat(tests)
# print(sat)

# -------------------
M=int(input())

ans = list()

for m in range(M):
    d, new_tst = list(map(int, input().split()))
    tests[d] = new_tst
    sat=calcSat(tests)
    ans.append(sat)

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

Submission status: Time Limit Exceeded

Solution code:
D=int(input())
c=list(map(int,input().split()))
s=[]
t=[]

for _ in range(D):
    ss=list(map(int,input().split()))
    s.append(ss)
for _ in range(D):
    tt=int(input())
    t.append(tt)

query=[]
M=int(input())
for _ in range(M):
    q=list(map(int,input().split()))
    query.append(q)

for i in range(M):
    last=[0]*26
    v=0
    t[query[i][0]-1]=query[i][1]
    for d in range(D):
        last[t[d]-1]=d+1
        decrease=0
        for j in range(26):
            decrease+=c[j]*(d+1-last[j])
        
        v+=s[d][t[d]-1]-decrease
    print(v)
    i+=1

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    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())
    dq = [tuple(map(int, input().split())) for i in range(M)]

    ret = 0
    for d, q in dq:
        A = [0]*26
        ret = 0
        t[d-1] = q
        for i in range(D):
            ret += s[i][t[i]-1]
            # print(ret)
            A[t[i]-1] = i+1
            for j in range(26):
                ret -= c[j] * (i+1 - A[j])
        print(ret)


main()

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
c = [0] + list(map(int, input().split()))
s = [[0]] + [[0] + list(map(int, input().split())) for _ in range(D)]
t = [int(input()) for _ in range(D)]
M = int(input())
dq = [list(map(int, input().split())) for _ in range(M)]

for m in range(M):
    last = [0] * 27
    d = 0
    ans = 0
    p, q = dq[m]
    t[p - 1] = q
    for i in t:
        d += 1
        for j in range(1, 27):
            if j == i:
                continue
            ans -= c[j] * (d - last[j])
        last[i] = d
        ans += s[d][i]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
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())))
t=[]
for _ in range(d):
    t.append(int(input()))
m=int(input())
q=[]
for _ in range(m):
    q.append(tuple(map(int,input().split())))

for k in range(m):
    ld=[-1]*26
    sc=0
    t[q[k][0]-1]=q[k][1]


    for i in range(d):
        sc+=s[i][t[i]-1]
        ld[t[i]-1]=i

        C=0
        for j in range(26):
            C+=c[j]*(i-ld[j])
        sc-=C
    print(sc)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from time import time

def scoring(c,s,t):
    score = 0
    from_last = np.zeros(26)
    for i in range(s.shape[0]):
        from_last = from_last+1
        score += s[i,t[i]-1]
        from_last[t[i]-1] = 0
        score = score - (c*from_last).sum()
    return score


D = int(input())
c = list(map(int,input().split()))
s = np.empty((D,26))
for i in range(D):
    s[i,:] = np.array(list(map(int,input().split())))
start = time()

t = []
for i in range(D):
    chosen = s[i,:].flatten().argmax()+ 1
    t.append(chosen)


score = scoring(c,s,t)
while time()-start < 1.99:
    i = np.random.randint(D)
    old = t[i]
    t[i] = np.random.randint(1,27)
    new_score = scoring(c,s,t)
    if new_score > score:
        score = new_score
    else:
        t[i] = old

for i in t:
	print(i)

print(time()-start)

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
C = [int(i) for i in input().split()]
scores = [[int(i) for i in input().split()] for j in range(D)]
t = [int(input()) for i in range(D)]
DC = [0]*26

def calcScore(t):
    score = []
    S = 0
    last = [0]*26
    for d in range(1,D+1):
        S += scores[d-1][t[d-1]-1]
        last[t[d-1]-1] = d
        for i in range(26):
            S -= C[i] * (d - last[i])
            DC[i] += (d - last[i])
        score.append(S)
    return score[-1]

ans = []
M = int(input())
for _ in range(M):
    d,q = [int(i) for i in input().split()]
    t[d-1] = q
    ans.append(calcScore(t))
    # dif = scores[d-1][q-1] - scores[d-1][t[d-1]-1]
    # difc = C[q-1] - C[t[d-1]-1]
    # for i in range(d-1, D):
    #     score[i] += dif + difc * (i - d + 2)
    # ans.append(score[-1])
print("\n".join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
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)]
d=int(input())
q=[list(map(int,input().split())) for _ in range(d)]

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)
    
    return points

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

Submission status: Time Limit Exceeded

Solution code:
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
D = int(readline())
C = list(map(int,readline().split()))
score = []
for i in range(D):
    s = list(map(int,readline().split()))
    score.append(s)
t = []
for i in range(D):
    a = int(readline())
    t.append(a)

M = int(readline())
change = []
for i in range(M):
    d,q = map(int,readline().split())
    change.append((d,q)) 


for i in range(M):
    d,q = change[i]
    t[d-1] = q
    S = 0
    last = [0] * 26
    for day in range(D):
        select = t[day]-1
        S += score[day][select]
        last[select] = day+1
        for i in range(26):
            S -= C[i] * (day+1-last[i]) 
    print(S)

Submission status: Time Limit Exceeded

Solution code:
D = int(input())

last_list = [0 for i in range(27)]
c_list = list(map(int, input().split()))
c_list = [""] + c_list
# print(c_list)
S_list = [[]for i in range(D)]
P_list = [0 for i in range(27)]
for i in range(D):
    S_list[i] = list(map(int, input().split()))
    S_list[i] = [""] + S_list[i]
S_list = [""] + S_list
# print(S_list)


t_list = [""]
for i in range(D):
    t_list.append(int(input()))

for i in range(1,D+1):
    S = 0
    t = t_list[i]
    for j in range(1,27):
        if j == t:
            P_list[j] += S_list[i][j]
            last_list[j] = i
            # print(S_list[i][j])
        else:
            P_list[j] -= c_list[j] * (i-last_list[j])
    for i in range(1,27):
        S += P_list[i]
    # print(S)

M = int(input())
# print(M)
for m in range(M):
    last_list = [0 for i in range(27)]
    P_list = [0 for i in range(27)]
    C_A, C_B = map(int,input().split())
    t_new = t_list
    t_new[C_A] = C_B
    for i in range(1,D+1):
        S_new = 0
        t = t_new[i]
        for j in range(1,27):
            if j == t:
                P_list[j] += S_list[i][j]
                last_list[j] = i
                # print(S_list[i][j])
            else:
                P_list[j] -= c_list[j] * (i-last_list[j])
        for i in range(1,27):
            S_new += P_list[i]
    print(S_new)

Submission status: Time Limit Exceeded

Solution code:
import random
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())
dq = [tuple(map(int, input().split())) for i in range(M)]


ret = 0
for d, q in dq:
    A = [0]*26
    ret = 0
    t[d-1] = q
    for i in range(D):
        ret += s[i][t[i]-1]
        # print(ret)
        A[t[i]-1] = i+1
        for j in range(26):
            ret -= c[j] * (i+1 - A[j])
    print(ret)

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
c = list(map(int, input().split()))
s = [input().split() for _ in range(D)]
t = [int(input()) for _ in range(D)]
M = int(input())
dq = [map(int, input().split()) for _ in range(M)]
d, q = [list(i) for i in zip(*dq)]
for m in range(M):
    v = 0
    last = [0] * 26
    t[d[m] - 1] = q[m]
    for date in range(1, D + 1):
        last[t[date - 1] - 1] = date
        v += int(s[date - 1][t[date - 1] - 1])
        for i in range(26):
            v -= c[i] * (date - last[i])
    print(v)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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


t = [int(input().strip()) for _ in range(D)]
M = int(input())
d = [list(map(int,input().split())) for i in range(M)]

ans_arr = []
for j in range(M):
    t[d[j][0]-1] = d[j][1]
    ans = 0
    last = np.zeros(26)
    for i in range(D):
        last[t[i]-1] = i+1
        dec = c * (i+1-last)
        ans = ans + s[i][t[i]-1] - sum(dec)
    ans_arr.append(int(ans))   

for i in range(M):
    print(ans_arr[i])

Submission status: Time Limit Exceeded

Solution code:

import numpy as np


def read_input():
    d = int(input())
    c = list(map(int, input().split()))
    s = [list(map(int, input().split())) for _ in range(d)]
    return d, c, s


def simulate(d, c, s, t):
    """
    t : コンテスト番号列
    """
    last = {i: 0 for i in range(26)}

    def day_loss(curr):
        loss = 0
        for i, e in enumerate(c):
            loss += e * (curr - last[i])
        return loss
    
    sufficient = 0
    loss = 0
    hist = []
    for day in range(1, d + 1):
        contest = t[day - 1] - 1
        last[contest] = day
        sufficient += s[day - 1][contest]
        loss -= day_loss(day)
        hist.append(sufficient - loss)
    return sufficient - loss, hist


def submit():
    d, c, s = read_input()
    ans = [int(input()) - 1 for _ in range(d)] # 初期解を適当に設定

    def get_loss_matrix(ans):
        loss_matrix = np.zeros((26, d + 1))
        for day, a in enumerate(ans):
            loss_matrix[:, day + 1] += loss_matrix[:, day] + 1
            loss_matrix[a, day + 1] = 0
        return loss_matrix

    def contest_loss(loss_matrix, contest):
        return np.sum(loss_matrix[contest, :] * c[contest])
    
    def contest_gain(s, ans):
        gain = 0
        for i, a in enumerate(ans):
            gain += s[i][a]
        return gain

    loss_matrix = get_loss_matrix(ans)
    total_loss = 0
    for r in range(26):
        total_loss += contest_loss(loss_matrix, r)
    total_gain = contest_gain(s, ans)

    def get_new_status(d, q2):
        """
        d日目のコンテストを現状からq2に変更する
        """
        q1 = ans[d - 1]
        curr_q1_loss = contest_loss(loss_matrix, q1)
        curr_q2_loss = contest_loss(loss_matrix, q2)
        
        ans[d - 1] = q2
        # loss_matrixの再構築
        new_loss_matrix = get_loss_matrix(ans)

        # スコアの再計算
        new_total_loss = total_loss - curr_q1_loss - curr_q2_loss + \
                         contest_loss(new_loss_matrix, q1) + \
                         contest_loss(new_loss_matrix, q2)
        new_total_gain = total_gain - s[d - 1][q1] + s[d - 1][q2]
        return new_loss_matrix, new_total_gain, new_total_loss


    m = int(input())
    for _ in range(m):
        di, qi = map(int, input().split())
        qi -= 1
        loss_matrix, total_gain, total_loss = get_new_status(di, qi)
        print(int(total_gain - total_loss))


if __name__ == "__main__":
    submit()

Submission status: Time Limit Exceeded

Solution code:
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())
q_d = [0] * m
q_q = [0] * m

for i in range(m):
    q_d[i], q_q[i] = list(map(int, input().split()))

def calcSatisfactionRate(t):
    global d, c, s
    s_rate = 0
    last_days = [0] * 26
    for day in range(d):
        s_rate += s[day][t[day]-1]
        last_days[t[day]-1] = day + 1
        for j in range(26):
            s_rate -= c[j] * (day + 1 - last_days[j])
    return s_rate

s_rate = calcSatisfactionRate(t)
for j in range(m):
    t[q_d[j]-1] = q_q[j]
    s_rate = calcSatisfactionRate(t)
    print(s_rate)

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
cs = list(map(int,input().split()))
ss =[]
for i in range(D):
  ss.append(list(map(int,input().split())))
ts = []
for i in range(D):
  ts.append(int(input()))
M = int(input())
Qs =[]
for i in range(M):
    Qs.append(list(map(int,input().split())))
for r in range(len(Qs)):
  d= Qs[r][0]
  q= Qs[r][1]
  ts[d-1] = q
  last = [0] * 26
  total =0
  for i in range(len(ts)):
    t = ts[i]
    last[t-1] = i+1
    genten=0
    for j in range(len(cs)):
      genten += cs[j] *(i+1 - last[j])
    total += ss[i][t-1]-genten
  print(total)

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
C = list(map(int, input().split()))
S = list()
for i in range(D):
    tmp_ = list(map(int, input().split()))
    S.append(tmp_)
T = list()
for i in range(D):
    T.append(int(input()))
M = int(input())

for m in range(M):
    ret = 0
    lastd = [0] * 26
    d,q = map(int,input().split())
    T[d - 1] = q
    for i in range(D):
        ret += S[i][T[i]-1]
        lastd[T[i] - 1] = i + 1
        for j in range(26):
            ret -= C[j] * (i + 1 - lastd[j])
    print(ret)

Submission status: Time Limit Exceeded

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

import sys
stdin = sys.stdin
import numpy as np

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

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)

    def calc():
        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]]
            v -= (sum(c * (day - last_day)))
        return print(int(v))
    m = ni()
    for i in range(m):
        di, qi = na()
        t[di-1] = qi-1
        calc()

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
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())
dq = [list(map(int, input().split())) for _ in range(M)]

def calcScore(D, c, s, t):
    v = 0
    last_di = [0] * 26
    for d in range(D):
        i = t[d]
        v += s[d][i - 1]

        last_di[i - 1] = d + 1

        S = 0
        for j in range(len(c)):
            S += c[j] * (d + 1 - last_di[j])

        v -= S

    print(v)

for d, q in dq:
    t[d - 1] = q
    calcScore(D, c, s, t)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy

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

scores = [0] * (D + 1)
lasts = [[0] * 26 for _ in range(D + 1)]

def change(d, q):
    global scores, lasts, T
    T[d - 1] = q
    score = scores[d - 1]
    last = deepcopy(lasts[d - 1])
    for day, t in enumerate(T[d - 1:], d):
        score += S[day - 1][t - 1]
        last[t - 1] = day
        lasts[day] = deepcopy(last)
        for c, l in zip(C, last): score -= c * (day - l)
        scores[day] = score
    return scores[-1]

def init():
    change(1, T[0])
    return

M = int(input())
init()
for _ in range(M):
    d, q = map(int, input().split())
    print(change(d, q))