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

#変えたものだけに着眼する。
for quri in range(M):   
    target_day = dq[quri][0]
    target_num = t[target_day-1]
    change_num = dq[quri][1]

#変える前にtarget_numとchange_numが生み出した得点

    before_manzoku = 0
    last_day_t = 0
    last_day_c = 0
    for day in range(1,D+1):
        contest_number = t[day-1]
        last_day_t += 1
        last_day_c += 1
        if contest_number == target_num:
            before_manzoku += s[day-1,contest_number-1]
            last_day_t =0
        elif contest_number == change_num:
            before_manzoku += s[day-1,contest_number-1]
            last_day_c =0
        before_manzoku -=(last_day_t * c[target_num-1]+last_day_c * c[change_num-1])

#変えたあとにtarget_numとchange_numが生み出した得点

    t[dq[quri][0]-1] = dq[quri][1]

    after_manzoku = 0
    last_day_t = 0
    last_day_c = 0
    for day in range(1,D+1):
        contest_number = t[day-1]
        last_day_t += 1
        last_day_c += 1
        if contest_number == target_num:
            after_manzoku += s[day-1,contest_number-1]
            last_day_t =0
        elif contest_number == change_num:
            after_manzoku += s[day-1,contest_number-1]
            last_day_c =0
        after_manzoku -=(last_day_t * c[target_num-1]+last_day_c * c[change_num-1])
    be_af_manzoku = after_manzoku - before_manzoku
    manzoku += be_af_manzoku
    print(manzoku)

Submission status: Time Limit Exceeded

Solution code:
def main():
    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 = 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:
#!/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:
import copy
D=int(input())
ListC = list(map(int, input().split()))
dictC={}
dictD = {}
for i in range (1,27):
  dictC[i] = int(0)
  dictD[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):
  dictC = copy.deepcopy(dictD)
  ListT2[ListM[i][0]-1] = ListM[i][1]
  print(calc_figure(ListS, ListT2, ListC, dictC))

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 = 0

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

for m in range(M):
    T[dd[m] - 1] = qq[m]
    score = 0
    for d in range(1, 1 + D):
        score += S[d - 1][T[d - 1] - 1] - \
            sum([C[i]*(d - last(d, i, T)) for i in range(26)])

    print(score)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
  
def resolve():
    d = int(input())
    ci = list(map(int, input().split()))
    si = [list(map(int, input().split())) for _ in range(d)]
    answers = [int(input()) for _ in range(d)]

    #print(d, ci, si, answers)

    num_que = int(input())
    que = [list(map(int, input().split())) for _ in range(num_que)]
    #print(num_que, que)

    # queによる変更
    for q in range(num_que):
        answers[que[q][0]-1] = que[q][1]

        # 和の計算
        score_now = 0
        # コンテストごとの最後の実行日
        last_dates = [-1]*26
        for date in range(d):
            answer = answers[date]
            score_now += si[date][answer-1]

            last_dates[answer-1] = date
            for c, last_date in zip(ci, last_dates):
                score_now -= c*(date - last_date)
        # 最終スコア
        print(score_now)
resolve()

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 = map(int,input().split())
  ts[d-1] = 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:
from operator import mul

D=int(input())
clist=list(map(int,input().split()))
slist=[]
for i in range (D):
    s=list(map(int,input().split()))
    slist.append(s)
tlist=[]
for i in range(D):
    t=int(input())
    tlist.append(t)
changelist=[]
D2=int(input())
for i in range (D2):
    change=list(map(int,input().split()))
    changelist.append(change)

# D=5
# clist=[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]
# slist=[[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]]
# tlist=[1, 17, 13, 14, 13]
# D2=5
# changelist=[[1, 7], [4, 11], [3, 4], [5, 24], [4, 19]]

for j in range (D2):
    tlist[changelist[j][0]-1]=changelist[j][1]
    noheldsday=[0]*26
    benefit=0    
    
    for i in range (D):
        _noheldsday=list(map(lambda x: x+1,noheldsday))
        _noheldsday[tlist[i]-1]=0
        unpleasant=list(map(mul,clist,_noheldsday))
        
        v=slist[i][tlist[i]-1]-sum(unpleasant)
        benefit+=v
        noheldsday=_noheldsday
    print(benefit)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


def solve_base_score(dd, c_arr, s_arr, t_arr):
    last_d = np.zeros(26, dtype=np.int64) - 1
    score = 0
    for d in range(dd):
        score += s_arr[d, t_arr[d]]
        last_d[t_arr[d]] = d
        score -= (c_arr * (d - last_d)).sum()
    return score


def solve(dd, c_arr, s_arr, t_arr, m, dq_list):
    compare_score = solve_base_score(dd, c_arr, s_arr, t_arr)
    score_d = np.zeros(dd, dtype=np.int64)
    missing_d = np.zeros((dd, 26), dtype=np.int64)
    for d in range(dd):
        score_d[d] = s_arr[d, t_arr[d]]
        if d == 0:
            missing_d[d, :] = 1
        else:
            missing_d[d, :] = missing_d[d - 1, :] + 1
        missing_d[d, t_arr[d]] = 0
    score = score_d.sum() - (c_arr * missing_d).sum()
    # print(compare_score, score)
    assert compare_score == score

    res_list = []
    for i in range(m):
        d0_, q0_ = dq_list[i]
        d0 = d0_ - 1
        q0 = q0_ - 1
        p0 = t_arr[d0]
        # print(d0, p0, q0)
        t_arr[d0] = q0

        score += s_arr[d0, q0]
        score -= s_arr[d0, p0]
        score_d[d0] = s_arr[d0, q0]
        score += (c_arr[q0] * missing_d[:, q0]).sum()
        score += (c_arr[p0] * missing_d[:, p0]).sum()
        for d in range(dd):
            if d == 0:
                missing_d[d, p0] = 1
                missing_d[d, q0] = 1
            else:
                missing_d[d, p0] = missing_d[d - 1, p0] + 1
                missing_d[d, q0] = missing_d[d - 1, q0] + 1
            if t_arr[d] == p0:
                missing_d[d, p0] = 0
            elif t_arr[d] == q0:
                missing_d[d, q0] = 0

        score -= (c_arr[q0] * missing_d[:, q0]).sum()
        score -= (c_arr[p0] * missing_d[:, p0]).sum()

        res_list.append(score)

    return res_list


def main():
    d = np.int64(input())
    c_arr = np.array(list(map(int, input().split()))).astype(np.int64)
    s_arr = np.array([list(map(int, input().split())) for _ in range(d)]).astype(np.int64)
    t_arr = np.array([int(input()) for _ in range(d)]).astype(np.int64) - 1
    m = np.int64(input())
    dq_list = [list(map(int, input().split())) for _ in range(m)]
    res = solve(d, c_arr, s_arr, t_arr, m, dq_list)
    for r in res:
        print(r)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7
D = int(readline())
C = list(map(int,readline().split()))
S = [list(map(int,readline().split())) for i in range(D)]
t = [int(readline()) for i in range(D)]
def score():
    ans = 0
    minus = 0
    last = [0]*26
    for i in range(D):
        ans += S[i][t[i]-1]
        minus = 0
        last[t[i]-1] = i+1
        for j in range(26):
            minus += C[j]*(i-last[j]+1)
        ans -= minus
    print(ans)
M = int(readline())
for m in range(M):
    d,q = map(int,readline().split())
    t[d-1] = q
    score()

Submission status: Time Limit Exceeded

Solution code:
# モジュールのインポート
import numpy as np

# 標準入力を取得
D = int(input())
c = list(map(int, input().split()))
s = []
for d in range(D):
    s_d = list(map(int, input().split()))
    s.append(s_d)
t = []
for d in range(D):
    t_d = int(input())
    t.append(t_d)
M = int(input())
d, q = [], []
for m in range(M):
    d_m, q_m = list(map(int, input().split()))
    d.append(d_m)
    q.append(q_m)

c = np.array(c)
s = np.array(s)
t = np.array(t)
d = np.array(d)
q = np.array(q)

# 求解処理
# 初期コスト計算


def cost(t: np.ndarray) -> int:
    KIND = 26
    last = np.array([0 for i in range(KIND)])
    S = 0
    for day in range(1, D + 1):
        index_day = day - 1
        index_t_day = t[index_day] - 1
        S += s[index_day][index_t_day]
        last[index_t_day] = day
        S -= sum(c * (day - last))
    return S


S = cost(t)
for d_m, q_m in zip(d, q):
    index_d_m = d_m - 1
    t_d_m = t[index_d_m]
    index_t_d_m = t_d_m - 1
    index_q_m = q_m - 1
    # 増加処理の修正
    S = S - s[index_d_m][index_t_d_m] + s[index_d_m][index_q_m]
    # 減少処理の修正
    c_t_d_m = c[index_t_d_m]
    c_q_m = c[index_q_m]
    last_t_d_m = 0
    last_q_m = 0
    for day in range(1, D + 1):
        index_day = day - 1
        t_day = t[index_day]
        if t_day == t_d_m:
            last_t_d_m = day
        if t_day == q_m:
            last_q_m = day
        S = S + c_t_d_m * (day - last_t_d_m) + c_q_m * (day - last_q_m)

    t[index_d_m] = q_m
    last_t_d_m = 0
    last_q_m = 0
    for day in range(1, D + 1):
        index_day = day - 1
        t_day = t[index_day]
        if t_day == t_d_m:
            last_t_d_m = day
        if t_day == q_m:
            last_q_m = day
        S = S - c_t_d_m * (day - last_t_d_m) - c_q_m * (day - last_q_m)
    print(S)

Submission status: Time Limit Exceeded

Solution code:
import sys


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


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


if __name__ == '__main__':
    main()

Submission status: 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())
query = [list(map(lambda x: int(x)-1, input().split())) for _ in range(M)]

for d, q in query:
    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:
d = int(input())

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

s = []

for _ in range(d):
    temp = list(map(int,input().split()))

    s.append(temp)

choices = []

for _ in range(d):
    temp = int(input())

    choices.append(temp)

m = int(input())

queries = []

for _ in range(m):
    temp = list(map(int,input().split()))

    queries.append(temp)

changed_choices = [choices]

for day, new_choice in queries:
    temp = changed_choices[-1].copy()

    temp[day - 1] = new_choice

    changed_choices.append(temp)

def calc_point(point_list, interval, choice):
    point = 0

    for i, day in enumerate(interval):
        point -= c[i] * day

    point += point_list[choice - 1]

    return point

for temp_choices in changed_choices[1:]:
    interval = [0] * 26

    result = 0

    for i in range(d):
        choice = temp_choices[i]

        interval = [x + 1 for x in interval]

        interval[choice - 1] = 0

        result += calc_point(s[i], interval, choice)

    print(result)

Submission status: Time Limit Exceeded

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

def total_satisfaction(ts):
    ls = [0] * 26
    s = 0
    for i in range(d):
        t = ts[i]
        t -= 1
        s += sm[i][t]
        ls[t] = i + 1

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

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    d=int(input())
    c=list(map(int,input().split()))
    s=[list(map(int,input().split())) for _ in range(d)]
    last=[[0]*27 for _ in range(366)]
    srate=[0]
    T=[0]
    a=0
    for i in range(1,d+1):
        for j in range(27):
            last[i][j]=last[i-1][j]
        t=int(input())
        T.append(t)
        last[i][t]=i
        a+=s[i-1][t-1]
        for j in range(1,27):
            a-=c[j-1]*(i-last[i][j])
        srate.append(a)
    m=int(input())
    for i in range(m):
        D,Q=map(int,input().split())
        a=srate[D-1]
        for j in range(D,d+1):
            for k in range(27):
                last[j][k]=last[j-1][k]
            if j==D:
                T[j]=Q
            t=T[j]
            last[j][t]=j
            a+=s[j-1][t-1]
            for k in range(1,27):
                a-=c[k-1]*(j-last[j][k])
            srate[j]=a
        print(srate[-1])

if __name__ == '__main__':
    main()

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):
  d,q = map(int,input().split())
  k = [d,q]
  Qs.append(k)
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:
def sigma(d):
    r=0;
    for j in range(26):
        r+=c[j]*(d+1-last[j])
    return r

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
        v+=s[d][t[d]-1]-sigma(d)
    print(v)
    i+=1

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

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

    ret_count_list = []
    ret_val_list = []

    count_list = [0] * 26
    val = 0

    for idx in range(0, first):
        ret_count_list.append(arg_count_list[idx])
        ret_val_list.append(arg_val_list[idx])

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

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

        ret_count_list.append(count_list)
        ret_val_list.append(val)

    return val, ret_count_list, ret_val_list


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 i in range(D)]

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

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

def dissat(day):
  dissat = 0
  for i in range(26):
    if T[day-1]-1 == i:
      continue
    dissat += C[i]*(day-lastdays[i])

  return dissat    
    
def last(day):
  lastdays[T[day-1]-1] = day

# 
def calcscore(D):
  sat = 0
  for i in range(D):
    # dayi
    last(i)
    sat += S[i][T[i]-1] - dissat(i+1)
  print(sat)

# main
#lastdays = [0]*26
#calcscore(D)


# change contenst
for i in range(M):
  T[dq[i][0]-1] = dq[i][1]
  lastdays = [0]*26
  calcscore(D)

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())
query = [list(map(lambda x: int(x)-1, input().split())) for _ in range(M)]

for d, q in query:
    T[d] = q

    ans = []
    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
        ans.append(val)
    
    print(val)

Submission status: Time Limit Exceeded

Solution code:
D = int(input())#D=365
c = list(map(int, input().split()))#0<=c<=100
s = [list(map(int, input().split())) for _ in range(D)]#0<=s<=20000

t = [int(input()) for _ in range(D)]

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


def culc_value(t):
    last = [0] * 26
    value = 0
    for d in range(D):
        type = t[d]
        value += s[d][type - 1]
        last[type - 1] = d + 1
        for i in range(26):
            value -= c[i] * (d + 1 - last[i])
    return value


v_lastday = []
for d, q in dq:
    t[d - 1] = q
    v_lastday.append(culc_value(t))

for x in v_lastday:
    print(x)


"""
for i in range(D):
    print(v[i])
"""