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:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys


def input():
    return sys.stdin.readline()

def down_pleasure(c_list, day_num, contest_last_day):
    """その日の満足度低下を返す"""
    sum_down_pl = 0
    for i in range(26):
        sum_down_pl += c_list[i] * (day_num - contest_last_day[i])

    return sum_down_pl


def calc_pleasure(s_list, t_list, d, c_list, contest_last_day):
    pleasure = 0

    for day, t_num in zip(range(d), t_list):
        pleasure += s_list[day][t_num-1]
        contest_last_day[t_num-1] = day + 1
        pleasure -= down_pleasure(c_list, day+1, contest_last_day)

    return pleasure


def resolve():
    d = int(input().rstrip())
    c_list = list(map(int, input().split()))
    s_list = [list(map(int, input().split())) for i in range(d)]
    t_list = []

    for i in range(d):
        t_list.append(int(input().rstrip()))

    m = int(input().rstrip())
    d_list = [0] * m
    q_list = [0] * m
    for i in range(m):
        d_list[i], q_list[i] = map(int, input().split())

    contest_last_day = []
    for i in range(26):
        contest_last_day.append(0)

    # old_pleasure = calc_pleasure(s_list,t_list,d, c_list, contest_last_day)
    """
    for i in range(26):
        contest_last_day[i] = 0
    """
    for i in range(m):
        change_d = d_list[i]
        change_q = q_list[i]
        # old = t_list[change_d-1]
        t_list[change_d-1] = change_q
        new_pleasure = calc_pleasure(s_list, t_list, d, c_list, contest_last_day)
        for j in range(26):
            contest_last_day[j] = 0
        print(new_pleasure)
        """
        if new_pleasure < old_pleasure:
            t_list[change_d-1] = old
        """


if __name__ == "__main__":
    resolve()

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())))
t=[]
for _ in range(D):
  t.append(int(input()))
M=int(input())
q=[]
for _ in range(M):
  q.append(list(map(int,input().split())))
g=0
v=[]
p=0
def w(g,v,p):
  for d in range(p,D):
    a=s[d][t[d]-1]
    b=0
    for i in range(26):
      for j in range(d+1,0,-1):
        if t[j-1]==i+1:
          b+=c[i]*(d+1-j)
          break
      else:
        b+=c[i]*(d+1)
    g+=a-b
    v.append(g)
w(g,v,p)
for k in range(M):
  p=q[k][0]-1
  t[p]=q[k][1]
  v=v[0:p]
  g=v[-1] if len(v)>0 else 0
  w(g,v,p)
  print(v[-1])

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)]
sumc = sum(C)
last = [0 for i in range(26)]
check = [0 for i in range(26)]
con = []

ans = 0
for i in range(D):
    t = int(input())
    last[t-1] = i+1
    ans += S[i][t-1]
    check[t-1] += 1
    con.append(t)
    for j in range(26):
        ans -= C[j]*(i+1 - last[j])

M = int(input())
for i in range(M):
    d, q = map(int, input().split())
    e = con[d-1] #i日目にやるコンテスト
    l1 = -1
    l2 = -1
    tmpe = 0
    tmpq = 0
    f1 = D
    f2 = D
    for j in range(D):
        if check[e-1] == 0 and check[q-1] == 0:
            break
        if tmpe == 1 and tmpq == 1:
            break
        if j < d-1:
            if con[j] == e:
                l1 = j #変更前のコンテストを直前の最後にいつやったか
            if con[j] == q:
                l2 = j #変更後のコンテストを直前の最後にいつやったか
        if j > d-1:
            if con[j] == e and tmpe == 0:
                f1 = j #変更前のコンテストを直後にいつやったか
                tmpe = 1
            if con[j] == q and tmpq == 0:
                f2 = j #変更後のコンテストを直後にいつやったか
                tmpq = 1
    con[d-1] = q
    check[e-1] -= 1
    check[q-1] += 1
    ans = ans - S[d-1][e-1] + S[d-1][q-1] + C[q-1]*(f2-d+1)*(d-l2-1) - C[e-1]*(f1-d+1)*(d-l1-1)
    print(ans)

Submission status: Time Limit Exceeded

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

M = int(input())
for _ in range(M):
    last = [0] * 27
    manzoku = [0] * 27
    d, q = list(map(int, input().split()))
    t[d] = q
    for i in range(1, D+1):
        manzoku[t[i]] += s[i-1][t[i]-1]
        last[t[i]] = i
        for j in range(1, 27):
            manzoku[j] -= c[j] * (i - last[j])
        
        result = 0
        for k in range(27):
            result += manzoku[k]

    print(result)

Submission status: Time Limit Exceeded

Solution code:
def intro_heuristics_c():
    # 本番テストケースは365
    D = int(input())

    # コンテストタイプごとの満足度の下がりやすさ
    C = list(map(int, input().split()))

    # 満足度row日目にコンテストcolタイプを開催したときの満足度の増加
    S = []
    for _ in range(D):
        sday = list(map(int, input().split()))
        S.append(sday)

    # 回答(出力)
    T = [int(input()) for _ in range(D)]

    # 変更するクエリ
    M = int(input())
    Q = [tuple(map(int, input().split())) for _ in range(M)]

    def calc_score(T):
        # さいごに開催したコンテストの日付
        last = [-1] * 26
        # 満足度と不満度を計算して出力
        val = 0
        for d in range(D):
            idx = T[d] - 1
            satis = S[d][idx]
            last[idx] = d
            complain = 0
            for j in range(26):
                complain += C[j] * (d - last[j])
            val += satis - complain
        return val

    for d, q in Q:
        T[d-1] = q
        score = calc_score(T)
        print(score)

intro_heuristics_c()

Submission status: Time Limit Exceeded

Solution code:
#Aの入力

D=int(input())
#D=5

c = list(map(int, input().split()))
#c = list(map(int, '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'.split()))

s = []#Dx26の行列
for i in range(D):
    s += [list(map(int, input().split()))]
#s=[]
    
#s+=[list(map(int, '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'.split()))]
#s+=[list(map(int, '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'.split()))]
#s+=[list(map(int, '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'.split()))]
#s+=[list(map(int, '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'.split()))]
#s+=[list(map(int, '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'.split()))]

t = [int(input()) for i in range(D)]#Aの出力 (コンテスト名　0~25) len = D
#t=[1,17,13,14,13]

M=int(input())
#M=5

d = []
q = []

#d=[1,4,3,5,4]
#q=[7,11,4,24,19]

for i in range(M):
    di,qi = map(int, input().split())
    d+= [di]
    q += [qi]

for m in range(M):
    
    t[d[m]-1] = q[m]

    #print(t)
    
    last = [0 for i in range(len(c))]#最後に行われた日

    value = 0

    #v = []#len = 26

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


    #Bの出力
    #for i in range(D):
        #print(v[i])
        
    print(value)

Submission status: Time Limit Exceeded

Solution code:
f=lambda:[*map(int,input().split())]
D=int(input())
c=f()
S,t=[],[]
for i in range(D): S+=[f()]
for i in range(D): t+=[int(input())]
m=int(input())
for i in range(m):
  d,q=f()
  t[d-1]=q
  v=0
  l=[0]*26
  for i in range(D):
    l[t[i]-1]=i+1
    v+=S[i][t[i]-1]
    for j in range(26):
      v-=c[j]*(i+1-l[j])
  print(v)

Submission status: Time Limit Exceeded

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

    for p, q in dq:
        t[p - 1] = q
        last = [0] * 27
        ans = 0
        d = 0
        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)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

for i in range(M):
  t[d[i]-1] = q[i]
  ans = 0
  last_date = [0]*26
  for day in range(D):
    contest = t[day]-1
    ans += s[day][contest]
    last_date[contest] = day+1
    for j in range(26):
      ans -= c[j] * (day+1 - last_date[j])

  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import copy


def score(D, c, s, t):
    S = 0
    last = [0 for _ in range(26)]
    score_by_day = []

    for day in range(1, D+1):
        ctype = t[day-1]-1
        S += s[day-1][ctype]
        last[ctype] = day

        S -= sum(c[i]*(day-last[i]) for i in range(26))
        score_by_day.append(S)

    return score_by_day


def inputs(get_t=False):
    D = int(input())
    c = list(map(int, input().split()))
    s = []
    for d in range(D):
        sd = list(map(int, input().split()))
        s.append(sd)

    if get_t:
        t = []
        for d in range(D):
            t.append(int(input()))
        return D, c, s, t

    return D, c, s


def query():
    M = int(input())
    dd, qq = [], []
    for _ in range(M):
        d, q = map(int, input().split())
        dd.append(d)
        qq.append(q)
    return M, dd, qq


def output(types):
    for t in types:
        print(t)


if __name__ == "__main__":
    D, c, s, t_0 = inputs(get_t=True)
    M, dd, qq = query()
    t = copy.copy(t_0)
    for d, q in zip(dd, qq):
        t[d-1] = q
        print(score(D, c, s, t)[-1])

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
C = [int(x) for x in input().split()]
S = []
for i in range(D):
    S.append([int(x) for x in input().split()])
T = [int(input()) for i in range(D)]

M = int(input())
dd = []
qq = []
for i in range(M):
    d, q = (int(x) for x in input().split())
    dd.append(d)
    qq.append(q)


def last(d, i, t):
    l = 0
    for j in range(1, d + 1):
        if t[j - 1] == i + 1:
            l = j
    return l

score = sum([S[d - 1][T[d - 1] - 1] - sum([C[i]*(d - last(d, i, T))
                                           for i in range(26)]) for d in range(1, 1 + D)])

for m in range(M):
    T[dd[m] - 1] = qq[m]
    score = sum([S[d - 1][T[d - 1] - 1] - sum([C[i]*(d - last(d, i, T))
                                               for i in range(26)]) for d in range(1, 1 + D)])
    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)]
out = [int(input()) for _ in range(D)]

def satsfc():
    sat = 0
    last = [0] * 26
    for d in range(D):
        j = out[d] - 1
        last[j] = d + 1
        for i in range(26):
            sat -= (d + 1 - last[i]) * c[i]
        sat += s[d][j]
    return sat

m = int(input())
for i in range(m):
    v, q = map(int, input().split())
    out[v - 1] = q
    print(satsfc())

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())-1 for _ in range(D)]
M = int(input())

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

    val = 0
    sch = [0]*26
    for d in range(D):
        day = d+1
        t = T[d]
        sch[t] = day

        down = 0
        for i in range(26):
            down += C[i]*(day - sch[i])

        val = val + S[d][t] - down
    
    print(val)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

input = sys.stdin.readline

D = int(input())
c = np.array(list(map(int, input().split())), dtype=int)
S = np.array([list(map(int, input().split())) for _ in range(D)], dtype=int)
T = np.array([int(input()) for _ in range(D)], dtype=int)
M = int(input())
dq = np.array([tuple(map(int, input().split())) for _ in range(M)])
dissatisfactions = np.zeros((D+1, 26), dtype=int)


def findzero(a, after):
    try:
        return after+np.where(a[after:]==0)[0][0]
    except IndexError:
        return len(a)


v = 0
for i, (s, t) in enumerate(zip(S, T)):
    v += s[t-1]
    dissatisfactions[i+1] = dissatisfactions[i] + c
    dissatisfactions[i+1, t-1] = 0
    v -= np.sum(dissatisfactions[i+1])

for d, q in dq:
    pre = T[d-1]
    new = q
    pre0 = findzero(dissatisfactions[:, pre-1], d+1)
    new0 = findzero(dissatisfactions[:, new-1], d+1)

    # 値の更新
    v += S[d - 1, new - 1] - S[d - 1, pre - 1]
    v += (dissatisfactions[d, new-1])*(new0-d) - (dissatisfactions[d-1, pre-1]+c[pre-1])*(pre0-d)
    # 配列書き換え
    T[d - 1] = new
    dissatisfactions[d:new0, new-1] -= dissatisfactions[d, new-1]
    dissatisfactions[d:pre0, pre-1] += dissatisfactions[d-1, pre-1]+c[pre-1]
    print(v)

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

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())
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())
for r in range(M):
  d,q = input().split()
  ts[int(d)-1] = int(q)
  last = [0] * 26
  total =0
  for i in range(D):
    t = ts[i]
    last[t-1] = i+1
    genten=0
    for j in range(26):
      genten += cs[j] *(i+1 - last[j])
    total += ss[i][t-1]-genten
  print(total)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
import fractions
import bisect
import queue
import heapq
import collections
import itertools
import random
sys.setrecursionlimit(4100000)


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

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


class Schejule:

    def __init__(self, sche):
        self.base = sche
        self.last = [0] * 26
        self.y = 0

    def get_score(self):
        self.y = 0
        for d in range(D):
            self.y += S[d][self.base[d]]

        for d in range(D):
            self.last[self.base[d]] = d + 1

            for j in range(26):
                self.y -= C[j] * (d+1 - self.last[j])

    def change_one(self, day, to):

        org = self.base[day]

        # 差分
        div = 0

        # その日の満足度の変化
        div += S[day][to] - S[day][org]

        # 損失
        org_loss = 0
        cha_loss = 0

        org_last = 0
        cha_last = 0
        for d in range(D):
            if self.base[d] == org:
                org_last = d + 1
            elif self.base[d] == to:
                cha_last = d + 1

            org_loss +=  C[org] * (d+1 - org_last)
            cha_loss +=  C[to ] * (d+1 - cha_last)

        def_loss = cha_loss + org_loss


        org_loss = 0
        cha_loss = 0

        org_last = 0
        cha_last = 0
        for d in range(D):
            if d != day:
                if self.base[d] == org:
                    org_last = d + 1
                elif self.base[d] == to:
                    cha_last = d + 1
            else:
                cha_last = d+1

            org_loss +=  C[org] * (d+1 - org_last)
            cha_loss +=  C[to ] * (d+1 - cha_last)

        aft_loss = cha_loss + org_loss


        # 全体の差分
        div -= aft_loss - def_loss

        # ε-greedy
        #if div > 0 or random.randint(0, 9) >= 7:
        next_plan = self.base
        next_plan[day] = to

        sche_next = Schejule(next_plan)
        sche_next.y = self.y + div

        return sche_next
        #else:
        #    return self



#T = [0] * D

#for i in range(D):
#    max_day = 0
#    for j in range(26):
#        if S[i][max_day] < S[i][j]:
#            max_day = j
#    T[i] = max_day

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


sche_base = Schejule(T)
sche_base.get_score()


best_score = sche_base.y
best_set = T

#print(sche_base.y)

#print(*sche_base.base)

M = int(input())



for i in range(M):
    #d = random.randint(0, D - 1)
    #t = random.randint(0, 26 - 1)

    d,t = map(int,input().split())
    d -=1
    t -= 1

    sche_base  = sche_base.change_one(d, t)

    if best_score < sche_base.y:
        best_score = sche_base.y
        best_set = sche_base.base
    #print(*sche_base.base)

    print(sche_base.y)

#for i in range(D):
#    print(best_set[i] + 1)


#print(best_score)

Submission status: Time Limit Exceeded

Solution code:
import random as rand
days = int(input())
clast = list(map(int,input().split()))

allpref = [] #allpref[day][contest]
for i in range(days):
    allpref.append(list(map(int,input().split())))

def greedy():

    global allpref,days,clast
    donelist = [0]*26
    contestlist = []

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

        contestlist.append(contest+1)

    return contestlist

def scoreing(givenlist):
    global days,clast,allpref
    resultlist = []
    result = 0
    donelist = [0]*26
    for i in range(days):
        held = givenlist[i]

        donelist[held-1] = i+1
        zanen = sum([clast[j]*((i+1)-donelist[j]) for j in range(26)])

        result += allpref[i][held-1] - zanen
        resultlist.append(result)
    return resultlist

def kyokusho(givenlist,dlist,qlist):
    global days
    t = givenlist[:]
    for d,q in zip(dlist,qlist):
        #d = rand.randint(0,days-1);q=rand.randint(1,26)
        old = t[d-1] # 後で戻せるように元の値を記憶しておく
        t[d-1] = q
        scoreing()
        #if scoreing(givenlist) > scoreing(t):
        #    t[d-1] = old

    return t

clist = []
for i in range(days):
    clist.append(int(input()))
dlist = [];qlist = []
for i in range(int(input())):
    d,q = map(int,input().split())
    dlist.append(d);qlist.append(q)


t = clist[:]
for d,q in zip(dlist,qlist):
    #d = rand.randint(0,days-1);q=rand.randint(1,26)
    old = t[d-1] # 後で戻せるように元の値を記憶しておく
    t[d-1] = q
    print(scoreing(t)[days-1])
#kyokusho(clist,dlist,qlist)

#for cont in scoreing(kyokusho(clist,dlist,qlist)):
#    print(cont)

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, count_list, val_list = calcVal(sList, tList, cList, d, 0, [0] * d, [0] * d)

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

        val, count_list, val_list = calcVal(sList, temp_tlist, cList, d, qList[qidx][0] -1, count_list, val_list)
        #if (opposit_val > val):
        #val = opposit_val
        tList = temp_tlist

        print(val)



def calcVal(sList, tList,cList, d, first, arg_count_list, arg_val_list):

    count_list = [0] * 26
    val = 0

    if (first > 0):
        count_list = arg_count_list[first-1]
        val = arg_val_list[first-1]

    for idx in range(first, 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])

        arg_count_list[idx] = count_list
        arg_val_list[idx] = (val)

    return val, arg_count_list, arg_val_list


if __name__ == '__main__':
    main()