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:
_,C,*I=[[*map(int,t.split())]for t in open(0)]
for d,q in I[731:]:
 I[d+364][0]=q;i,R,P,*L=[0]*29
 while i<365:t=I[i+365][0]-1;P+=sum(C)+(~i+L[t])*C[t];R+=I[i][t]-P;i+=1;L[t]=i
 print(R)

Submission status: Time Limit Exceeded

Solution code:
(D,),C,*I=[[*map(int,t.split())]for t in open(0)]
for d,q in I[D-~D:]:
 I[d-1+D][0]=q;i,R,P,*L=[0]*29
 while i<D:t=I[i+D][0]-1;P+=sum(C)+(~i+L[t])*C[t];R+=I[i][t]-P;i+=1;L[t]=i
 print(R)

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left


class score:
    def __init__(self,t) -> None:
        score = 0
        last = [[0] for i in range(26)]
        for i in range(D):
            ti = t[i]
            ti_last = last[ti][-1]
            score += s[i][ti]-c[ti]*(i+1-ti_last)*(i-ti_last)//2
            last[ti].append(i+1)
        DD = D+1
        for tj in range(26):
            d = DD-last[tj][-1]
            score -= c[tj]*d*(d-1)//2
        self.score = score
        self.t = t


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())
dq = [tuple(map(int,input().split())) for i in range(m)]
for di,qi in dq:
    t[di-1] = qi-1
    sc = score(t)
    print(sc.score)

Submission status: Time Limit Exceeded

Solution code:
_,C,*I=[list(map(int,o.split()))for o in open(0)]
for d,q in I[731:]:
 I[d+364][0]=q;L=[0]*26;R=P=0
 for i in range(365):t=I[i+365][0]-1;P+=sum(C)-(i+1-L[t])*C[t];R+=I[i][t]-P;L[t]=i+1
 print(R)

Submission status: Time Limit Exceeded

Solution code:
def P(s):
  L = [0] * 26
  R = P = 0
  for i in range(D):
    t = I[i + D][0] - 1
    R += I[i][t]
    P += s - (i + 1 - L[t]) * C[t]
    R -= P
    L[t] = i + 1
  return R
(D,), C, *I = [list(map(int, o.split())) for o in open(0)]
for d, q in I[2*D + 1:]:
  I[d - 1 + D][0] = q
  print(P(sum(C)))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left, bisect_right
import random
import sys

input = sys.stdin.readline


class score:
    def __init__(self, t):
        ds = [[0] for i in range(26)]
        for i, ti in enumerate(t):
            ds[ti - 1].append(i+1)
        for i in range(26):
            ds[i].append(D+1)
        self.ds = ds
        self.t = t

    def first_score(self):
        last = [0] * 26
        score = 0
        for i, ti in enumerate(self.t):
            score += S[i][ti - 1]
            last[ti - 1] = i + 1
            for j in range(26):
                score -= C[j] * ((i + 1) - last[j])
        self.score = score
        return score

    def change(self, day, new_ti):
        score = self.score
        day -= 1
        old_ti = self.t[day]-1
        new_ti -= 1
        score -= S[day][old_ti]
        score += S[day][new_ti]
        

        self.score = score
        return self.score


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)]
s = score(T)
s.first_score()
for i in range(int(input())):
    di, qi = map(int, input().split())
    s.t[di-1] = qi
    print(s.first_score())

Submission status: Time Limit Exceeded

Solution code:
import bisect
import random
import sys

input = sys.stdin.readline


class score:
    def __init__(self, t):
        self.t = t

    def first_score(self):
        last = [0]*26
        score = 0
        for i,ti in enumerate(self.t):
            score += S[i][ti - 1]
            last[ti-1] = i + 1
            for j in range(26):
                score -= C[j] * ((i+1) - last[j])
        self.score = score
        return score

    def update(self,d,q):
        return self.score

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)]
s = score(T)
s.first_score()
for i in range(int(input())):
    di,qi = map(int,input().split())
    s.t[di-1] = qi
    print(s.first_score())

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.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)]

score = 0
lasts = [[0] for i in range(26)]
for i,(s,a) in enumerate(zip(S,T)):
    score += s[a-1]
    lasts[a-1].append(i+1)
for j in range(26):
    lasts[j].append(D+1)

for j,(c,ls) in enumerate(zip(C,lasts)):
    for a,b in zip(ls,ls[1:]):
        score -= c * (b-a)*(b-a-1)//2

from bisect import insort
for d,q in DQ:
    p = T[d-1]
    T[d-1] = q
    score += (S[d-1][q-1] - S[d-1][p-1])
    for a,b in zip(lasts[p-1],lasts[p-1][1:]):
        score += C[p-1] * (b-a)*(b-a-1)//2
    for a,b in zip(lasts[q-1],lasts[q-1][1:]):
        score += C[q-1] * (b-a)*(b-a-1)//2
    i = lasts[p-1].index(d)
    del lasts[p-1][i]
    insort(lasts[q-1], d)
    for a,b in zip(lasts[p-1],lasts[p-1][1:]):
        score -= C[p-1] * (b-a)*(b-a-1)//2
    for a,b in zip(lasts[q-1],lasts[q-1][1:]):
        score -= C[q-1] * (b-a)*(b-a-1)//2
    print(score)

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)]

SELECT = []
for i in range(D):
    SELECT.append(int(input())-1)

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

L_ALL = [[0]*26 for _ in range(D)]
L = [0]*26
ans = 0
for i in range(D):
    ans += S[i][SELECT[i]]
    L[SELECT[i]]=i+1
    if i != 0:
        L_ALL[i] = L_ALL[i-1][:]
    L_ALL[i][SELECT[i]] = i+1
    for j in range(26):
        ans -= C[j]*(i+1-L[j])

for i in range(M):
    day = d[i]
    before = SELECT[day]
    after = q[i]
    ans -= S[day][before]
    ans += S[day][after]
    SELECT[day] = q[i]

    if day == 0:
        tmp = 0
    else:
        tmp = L_ALL[day-1][before]
    j = day
    while 0<=j<D and L_ALL[j][before]==day+1:
        L_ALL[j][before] = tmp
        ans -= C[before]*(day+1-tmp)
        j += 1

    if day == 0:
        tmp = 0
    else:
        tmp = L_ALL[day-1][after]
    j = day
    while 0<=j<D and L_ALL[j][after]==tmp:
        L_ALL[j][after]=day+1
        ans += C[after] * (day+1-tmp)
        j += 1

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from _collections import deque
def main():
    D = int(input())
    C = list(map(int,input().split()))
    S = deque([])
    for _ in range(D):
        S.append(list(map(int,input().split())))

    SELECT = deque([])
    for i in range(D):
        SELECT.append(int(input())-1)

    def score(selects):
        score = 0
        L = [0 for _ in range(26)]
        def calc(ans, select, n):
            for i, l in enumerate(L):
                if i != select:
                    ans -= C[i] * (n - L[i])
                else:
                    L[i] = n
            return ans

        for i,select in enumerate(selects):
            score += S[i][select]

            for j, l in enumerate(L):
                if j != select:
                    score -= C[j] * (i+1 - L[j])
                else:
                    L[j] = i+1
        return score

    M = int(input())
    for _ in range(M):
        i, s = map(int,input().split())
        SELECT[i-1]=s-1
        print(score(SELECT))

if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from _collections import deque
D = int(input())
C = list(map(int,input().split()))
S = deque([])
for _ in range(D):
    S.append(list(map(int,input().split())))

SELECT = deque([])
for i in range(D):
    SELECT.append(int(input())-1)

def score(selects):
    score = 0
    L = [0 for _ in range(26)]
    def calc(ans, select, n):
        for i, l in enumerate(L):
            if i != select:
                ans -= C[i] * (n - L[i])
            else:
                L[i] = n
        return ans

    for i,select in enumerate(selects):
        score += S[i][select]

        for j, l in enumerate(L):
            if j != select:
                score -= C[j] * (i+1 - L[j])
            else:
                L[j] = i+1
    return score

M = int(input())
for _ in range(M):
    i, s = map(int,input().split())
    SELECT[i-1]=s-1
    print(score(SELECT))

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
C = list(map(int,input().split()))
S = []
for _ in range(D):
    S.append(list(map(int,input().split())))

SELECT = []
for i in range(D):
    SELECT.append(int(input())-1)

def score(selects):
    score = 0
    L = [0 for _ in range(26)]
    def calc(ans, select, n):
        for i, l in enumerate(L):
            if i != select:
                ans -= C[i] * (n - L[i])
            else:
                L[i] = n
        return ans

    for i,select in enumerate(selects):
        score += S[i][select]
        score = calc(score, select, i+1)
    return score

M = int(input())
for _ in range(M):
    i, s = map(int,input().split())
    SELECT[i-1]=s-1
    print(score(SELECT))

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 [0]*D]
t=[int(input()) for i in [0]*D]
m=int(input())
r=[list(map(int,input().split()))for i in [0]*m]
for a in r:
    t[a[0]-1]=a[1]
    k=0
    n=1
    p=[0]*26
    for i in t:
        k+=s[n-1][i-1]
        p[i-1]=n
        k-=sum([(n-p[j])*c[j] for j in range(26)])
        n+=1

    print(k)

Submission status: Time Limit Exceeded

Solution code:
def scoring():
    score = 0
    last = [0] * 26
    for d in range(len(out)):
        last[out[d]] = d + 1
        score += S[d][out[d]]
        score -= sum((d + 1 - l) * c for l, c in zip(last, C))
    return score

def local_search(d, q, score):
    # old = out[d]
    out[d] = q
    tmp = scoring()
    # if tmp > score:
        # score = tmp
    # else:
        # out[d] = old
    return tmp

D = int(input())
C = list(map(int, input().split()))
S = []
for _ in range(D):
    s = list(map(int, input().split()))
    S.append(s)
out = [int(input()) - 1 for _ in range(D)]
res = scoring()
M = int(input())
for _ in range(M):
    d, q = map(int, input().split())
    res = local_search(d-1, q-1, res)
    print(res)

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())
for query in range(M):
  d, q = map(int, input().split())
  t[d-1] = q
  sat = 0
  last = [0 for i in range(26)]
  for day in range(D):
    sat += s[day][t[day]-1]
    last[t[day]-1] = day+1
    for i in range(26):
      sat -= c[i] * (day+1 - last[i])
  print(sat)

Submission status: Time Limit Exceeded

Solution code:
def scoring():
    score = 0
    last = [0] * 26
    for d in range(len(out)):
        last[out[d]] = d + 1
        score += S[d][out[d]]
        score -= sum((d + 1 - l) * c for l, c in zip(last, C))
    return score

def local_search(d, q, score):
    # old = out[d]
    out[d] = q
    tmp = scoring()
    # if tmp > score:
        # score = tmp
    # else:
        # out[d] = old
    return tmp

D = int(input())
C = list(map(int, input().split()))
S = []
for _ in range(D):
    s = list(map(int, input().split()))
    S.append(s)
out = [int(input()) - 1 for _ in range(D)]
res = scoring()
M = int(input())
for _ in range(M):
    d, q = map(int, input().split())
    res = local_search(d-1, q-1, res)
    print(res)

Submission status: Time Limit Exceeded

Solution code:
#input
D = int(input())
c_list = list(map(int, input().split()))

s_grid = []
for i in range(D):
    array = list(map(int, input().strip().split(' ')))
    s_grid.append(array)

t_list = [int(input()) -1 for i in range(D)] #task_list

M = int(input())
d_grid = []
for i in range(M):
    array = list(map(int, input().strip().split(' ')))
    d_grid.append(array)


def calculate_score(t_list):
    score = 0
    last_list = [0 for i in range(26)]
    for d in range(D):
        score += s_grid[d][t_list[d]]
        last_list = [n+1 for n in last_list]
        last_list[t_list[d]] = 0
        for i in range(26):
            score -= c_list[i]*last_list[i]
    return score

for i in range(M):
    j = d_grid[i][0] - 1
    t_list[j] = d_grid[i][1] -1
    score = calculate_score(t_list)
    print(score)

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())-1)
M = int (input())
d=[]
q=[]
for i in range(M):
    d_, q_ = map(int, input().split())
    d.append(d_-1)
    q.append(q_-1)
def findNext(td, d):
    for i in range(d+1,D):
        if td == t[i]:
            return i
    return D
def findPrev(td, d):
    for i in range(d-1,0,-1):
        if td == t[i]:
            return i
    return -1   
def calcDif(t, d, q):
    ans = 0
    td = t[d]
    prev_td = findPrev(td,d)
    prev_q = findPrev(q,d)
    next_td = findNext(td,d)
    next_q = findNext(q,d)
    # del the affect of (d,t[d])
    ans -= s[d][td]
    ans -=  c[td] * (d - prev_td) * (next_td - d)
    # add the affect of (d,q)
    ans += s[d][q]
    ans +=  c[q] * (d - prev_q) * (next_q - d)
    return ans
def printResult(t):
    for tt in t:
        print(tt)
def calc(t):
    v = 0
    last = [-1 for _ in range(26)]
    for d in range(D):
        v += s[d][t[d]]
        last[t[d]]=d
        for i in range(26):
            v -= c[i] * (d - last[i])
    return v

v = calc(t)
for i in range(M):
    di = d[i]
    qi = q[i]
    v += calcDif(t,di,qi)
    t[di] = qi
    # print(di,qi)
    # print(v)
    print(calc(t))

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())-1)
M = int (input())
d=[]
q=[]
for i in range(M):
    d_, q_ = map(int, input().split())
    d.append(d_-1)
    q.append(q_-1)
def findNext(td, d):
    for i in range(d+1,D):
        if td == t[i]:
            return i
    return D
def findPrev(td, d):
    for i in range(d-1,0,-1):
        if td == t[i]:
            return i
    return -1   
def calcDif(t, d, q):
    ans = 0
    td = t[d]
    prev_td = findPrev(td,d)
    prev_q = findPrev(q,d)
    next_td = findNext(td,d)
    next_q = findNext(q,d)
    # del the affect of (d,t[d])
    ans -= s[d][td]
    for dd in range(d,next_td):
        ans -=  c[td] * (d - prev_td)
    # add the affect of (d,q)
    ans += s[d][q]
    for dd in range(d,next_q):
        ans +=  c[q] * (d - prev_q)
    return ans
def printResult(t):
    for tt in t:
        print(tt)
def calc(t):
    v = 0
    last = [-1 for _ in range(26)]
    for d in range(D):
        v += s[d][t[d]]
        last[t[d]]=d
        for i in range(26):
            v -= c[i] * (d - last[i])
    return v

v = calc(t)
for i in range(M):
    di = d[i]
    qi = q[i]
    v += calcDif(t,di,qi)
    t[di] = qi
    # print(di,qi)
    # print(v)
    print(calc(t))

Submission status: Time Limit Exceeded

Solution code:
def func(s,x):
    last=[0]*26
    score=0
    for i,v in enumerate(x,1):
        last[v]=i
        c=0
        for j in range(26):
            c+=s[j]*(i-last[j])
        score+=s[i*26+v]-c
    return score
def main():
    d,*s=map(int,open(0).read().split())
    x=[t-1for t in s[26*-~d:d*27+26]]
    for d,q in zip(*[iter(s[27*-~d:])]*2):
        x[d-1]=q-1
        print(func(s,x))
main()

Submission status: Time Limit Exceeded

Solution code:
def func(s,x):
    last=[0]*26
    score=0
    for i,v in enumerate(x,1):
        last[v]=i
        c=0
        for j in range(26):
            c+=s[j]*(i-last[j])
        score=score+s[i*26+v]-c
    return score
def main():
    d,*s=map(int,open(0).read().split())
    x=[t-1for t in s[26*-~d:d*27+26]]
    for d,q in zip(*[iter(s[27*-~d:])]*2):
        x[d-1]=q-1
        print(func(s,x))
main()

Submission status: Time Limit Exceeded

Solution code:
class Heruistics:
    donelist = [0]*26
    result = 0 #使いまわしがだめ
    contestlist = [] #cont か contestかどっちかにする
    def __init__(self,days):
        self.days = days #ここは別の文字にする
        self.clast = list(map(int,input().split()))
        self.allpref = [] #allpref[day][contest]
        for i in range(days):
            self.allpref.append(list(map(int,input().split())))

    def scoring(self):
        self.result = 0
        self.donelist = [0]*26
        for i in range(self.days):
            cont = self.contestlist[i]
            self.donelist[cont-1] = i+1
            zanen = sum([self.clast[j]*((i+1)-self.donelist[j]) for j in range(26)]) #差分計算のために後から参照できるようにしておく。ひと手間。
            self.result += self.allpref[i][cont-1] - zanen #zenenよりいい変数名


    def greedy(self):
        for i in range(self.days):
            max = -10**10 #maxは関数であるのでmaxiとかにする
            result = 0
            contest = False
            for held in range(26):
                tempdonelist = self.donelist[:] #変数名が長い
                tempdonelist[held] = i+1
                zanen = sum([self.clast[j]*((i+1)-tempdonelist[j]) for j in range(26)])
                result = self.allpref[i][held] - zanen
                if result >= max:
                    max = result;contest = held

            self.donelist[contest] = i+1
            self.contestlist.append(contest+1)

    def prefcount(self,cont):
            result = 0
            self.donelist[cont-1] = 0
            for i in range(self.days):
                temp = self.contestlist[i]
                if cont == temp:
                    self.donelist[cont-1] = i+1
                result += self.clast[cont-1]*((i+1)-self.donelist[cont-1])
            return result

    def kyokusho(self,day,cont):
        old = self.contestlist[day-1]
        zen = self.prefcount(old) + self.prefcount(cont)
        self.contestlist[day-1] = cont
        go = self.prefcount(old) + self.prefcount(cont)
        self.result -= -(zen - go) + (self.allpref[day-1][old-1] - self.allpref[day-1][cont-1]) #ここは紙に書けばO(1)で解が求まるようになると思う。思うだけ




greed_heru = Heruistics(int(input()))
for i in range(greed_heru.days):
    greed_heru.contestlist.append(int(input())) #ここのinput周りは後からいじりやすいように全部関数でやる

M = int(input())
dq = []
for i in range(M):
    d,q = map(int,input().split())
    dq.append((d,q)) #tupleの方が高速じゃない？

greed_heru.scoring()
for i in dq:#dqをイテラブルにしろ
    greed_heru.kyokusho(i[0],i[1])
    print(greed_heru.result)

Submission status: Time Limit Exceeded

Solution code:
class Heruistics:
    donelist = [0]*26
    result = 0
    contestlist = []
    def __init__(self,days):
        self.days = days
        self.clast = list(map(int,input().split()))
        self.allpref = [] #allpref[day][contest]
        for i in range(days):
            self.allpref.append(list(map(int,input().split())))

    def scoring(self):
        self.result = 0
        self.donelist = [0]*26
        for i in range(self.days):
            cont = self.contestlist[i]
            self.donelist[cont-1] = i+1
            zanen = sum([self.clast[j]*((i+1)-self.donelist[j]) for j in range(26)])
            self.result += self.allpref[i][cont-1] - zanen


    def greedy(self):
        for i in range(self.days):
            max = -10**10
            result = 0
            contest = False
            for held in range(26):
                tempdonelist = self.donelist[:]
                tempdonelist[held] = i+1
                zanen = sum([self.clast[j]*((i+1)-tempdonelist[j]) for j in range(26)])
                result = self.allpref[i][held] - zanen
                if result >= max:
                    max = result;contest = held

            self.donelist[contest] = i+1
            self.contestlist.append(contest+1)

    def prefcount(self,cont):
            result = 0
            self.donelist[cont-1] = 0
            for i in range(self.days):
                temp = self.contestlist[i]
                if cont == temp:
                    self.donelist[cont-1] = i+1
                result += self.clast[cont-1]*((i+1)-self.donelist[cont-1])
            return result

    def kyokusho(self,day,cont):
        old = self.contestlist[day-1]
        zen = self.prefcount(old) + self.prefcount(cont)
        self.contestlist[day-1] = cont
        go = self.prefcount(old) + self.prefcount(cont)
        self.result -= -(zen - go) + (self.allpref[day-1][old-1] - self.allpref[day-1][cont-1])

greed_heru = Heruistics(int(input()))
for i in range(greed_heru.days):
    greed_heru.contestlist.append(int(input()))

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

greed_heru.scoring()
for i in range(M):
    greed_heru.kyokusho(dq[i][0],dq[i][1])
    print(greed_heru.result)

Submission status: Time Limit Exceeded

Solution code:
def read_input():
    D = int(input())
    C = input().split()
    C = [int(i) for i in C]
    S = [list(map(int, input().split())) for x in range(D)]
    T = [int(input()) for _ in range(D)]
    N = int(input())
    M = []
    Q = []
    for i in range(N):
        line = list(map(int, input().split()))
        M.append(line[0])
        Q.append(line[1])
    return D, C, S, T, N, M, Q


def scoring(S, D, T, C, M, Q):
    res = []
    last = [0 for _ in range(26)]
    final = 0
    for i in range(D):
        if i == M-1:
            T[i] = Q
        dec = 0
        last[T[i] - 1] = i + 1
        for j in range(26):
            dec += C[j] * (i - last[j] + 1)
        final += S[i][T[i] - 1] - dec
        res.append(final)
    return res


D, C, S, T, N, M, Q = read_input()
for i in range(N):
    res = scoring(S, D, T, C, M[i], Q[i])
    print(res[len(res)-1])

Submission status: Time Limit Exceeded

Solution code:
def read_input():
    D = int(input())
    C = input().split()
    C = [int(i) for i in C]
    S = [list(map(int, input().split())) for x in range(D)]
    T = [int(input()) for _ in range(D)]
    N = int(input())
    M = []
    Q = []
    for i in range(N):
        line = list(map(int, input().split()))
        M.append(line[0])
        Q.append(line[1])
    return D, C, S, T, N, M, Q


def scoring(S, D, T, C, M, Q):
    res = []
    last = [0 for _ in range(26)]
    final = 0
    for i in range(D):
        if i == M-1:
            T[i] = Q
        dec = 0
        for j in range(26):
            for loc, val in enumerate(T[:i + 1]):
                if val == j + 1:
                    last[j] = loc + 1
            dec += C[j] * (i - last[j] + 1)
        final += S[i][T[i] - 1] - dec
        res.append(final)
    return res


D, C, S, T, N, M, Q = read_input()
for i in range(N):
    res = scoring(S, D, T, C, M[i], Q[i])
    print(res[len(res)-1])

Submission status: Time Limit Exceeded

Solution code:
def data_input():
    """
    D: 開催日数 365
    C: C[i]はコンテストiを開催しないことで失う満足度
    S: S[d][i]はコンテストiをd日目に開催することで得られる満足度
    """
    D = int(input())
    C = tuple(map(int, input().split()))
    S = [list(map(int, input().split())) for _ in range(D)]

    return D, C, S


def get_score(D, C, S, T, interim=False):
    """入力D, C, Sと出力Tからスコアを計算する関数"""

    last = [0] * 26  # 0で初期化されている

    def decrease(d):
        """d日めにiを開催した時の満足度の減少を返す関数"""
        res = 0
        for i in range(26):
            res -= C[i] * (d+1 - last[i])
        return res

    v = 0
    for d, i in enumerate(T):
        last[i] = d + 1
        v += decrease(d)
        v += S[d][i]
        if interim and d != D-1:
            print(v)
    return v


D, C, S = data_input()

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

for m in range(M):
    d, q = map(int, input().split())
    T[d-1] = q - 1
    v = get_score(D, C, S, T, interim=False)
    print(v)

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()))

def calc(T):
    ans=0
    last=[0]*26
    for d in range(1,D+1):
        temp=0
        last[T[d-1]-1]=d
        for i in range(26):
            temp-=c[i]*(d-last[i])
        temp+=s[d-1][T[d-1]-1]
        ans+=temp
    return ans

M=int(input())

for i in range(M):
    day,q=map(int,input().split())
    t[day-1]=q
    ans=calc(t)
    print(ans)