Problem:


(Please read problem A first. The maximum score you can get by solving this problem C is 1, which will have almost no effect on your ranking.)

Beginner's Guide

"Local search" is a powerful method for finding a high-quality solution.
In this method, instead of constructing a solution from scratch, we try to find a better solution by slightly modifying the already found solution.
If the solution gets better, update it, and if it gets worse, restore it.
By repeating this process, the quality of the solution is gradually improved over time.
The pseudo-code is as follows.

solution = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
    slightly modify the solution (randomly)
    if the solution gets worse:
        restore the solution

For example, in this problem, we can use the following modification: pick the date d and contest type q at random and change the type of contest to be held on day d to q.
The pseudo-code is as follows.

t[1..D] = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
    pick d and q at random
    old = t[d] # Remember the original value so that we can restore it later
    t[d] = q
    if the solution gets worse:
        t[d] = old

The most important thing when using the local search method is the design of how to modify solutions.

If the amount of modification is too small, we will soon fall into a dead-end (local optimum) and, conversely, if the amount of modification is too large, the probability of finding an improving move becomes extremely small.

In order to increase the number of iterations, it is desirable to be able to quickly calculate the score after applying a modification.

In this problem C, we focus on the second point.
The score after the modification can, of course, be obtained by calculating the score from scratch.
However, by focusing on only the parts that have been modified, it may be possible to quickly compute the difference between the scores before and after the modification.
From another viewpoint, the impossibility of such a fast incremental calculation implies that a small modification to the solution affects a majority of the score calculation.
In such a case, we may need to redesign how to modify solutions, or there is a high possibility that the problem is not suitable for local search.
Let's implement fast incremental score computation.
It's time to demonstrate the skills of algorithms and data structures you have developed in ABC and ARC!

In this kind of contest, where the objective is to find a better solution instead of the optimal one, a bug in a program does not result in a wrong answer, which may delay the discovery of the bug.
For early detection of bugs, it is a good idea to unit test functions you implemented complicated routines.
For example, if you implement fast incremental score calculation, it is a good idea to test that the scores computed by the fast implementation match the scores computed from scratch, as we will do in this problem C.

Problem Statement

You will be given a contest schedule for D days and M queries of schedule modification.
In the i-th query, given integers d_i and q_i, change the type of contest to be held on day d_i to q_i, and then output the final satisfaction at the end of day D on the updated schedule.
Note that we do not revert each query. That is, the i-th query is applied to the new schedule obtained by the (i-1)-th query.

Input

Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A and the queries.

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}
t_1
t_2
\vdots
t_D
M
d_1 q_1
d_2 q_2
\vdots
d_M q_M

The constraints and generation methods for the input part are the same as those for Problem A.

For each d=1,\ldots,D, t_d is an integer generated independently and uniformly at random from {1,2,\ldots,26}.

The number of queries M is an integer satisfying 1\leq M\leq 10^5.

For each i=1,\ldots,M, d_i is an integer generated independently and uniformly at random from {1,2,\ldots,D}.

For each i=1,\ldots,26, q_i is an integer satisfying 1\leq q_i\leq 26 generated uniformly at random from the 25 values that differ from the type of contest on day d_i.

Output

Let v_i be the final satisfaction at the end of day D on the schedule after applying the i-th query.
Print M integers v_i to Standard Output in the following format:

v_1
v_2
\vdots
v_M

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192
1
17
13
14
13
5
1 7
4 11
3 4
5 24
4 19

Sample Output 1

72882
56634
38425
27930
42884

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case.

Next Step

Let's go back to Problem A and implement the local search algorithm by utilizing the incremental score calculator you just implemented!
For this problem, the current modification "pick the date d and contest type q at random and change the type of contest to be held on day d to q" is actually not so good. By considering why it is not good, let's improve the modification operation.
One of the most powerful and widely used variant of the local search method is "Simulated Annealing (SA)", which makes it easier to reach a better solution by stochastically accepting worsening moves.
For more information about SA and other local search techniques, please refer to the editorial that will be published after the contest.



Sample input:
5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192
1
17
13
14
13
5
1 7
4 11
3 4
5 24
4 19


Sample output:
72882
56634
38425
27930
42884

Submission status: Time Limit Exceeded

Solution code:
import copy


d = int(input())
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())
query = [list(map(int, input().split())) for i in range(m)]
contest_types = 26


# 最後にコンテストを行った日
last_days = {}
for c_type in range(contest_types):
    last_days[c_type] = 0

# 初期解の構築
ans = 0
for i in range(d):
    day = i + 1
    c_type = t[i] - 1
    ans += s[i][c_type]
    last_days[c_type] = day
    for c_type in range(contest_types):
        ans -= c[c_type] * (day - last_days[c_type])


for day, after_type in query:
    day -= 1
    before_type = t[day] - 1
    after_type -= 1

    diff = -s[day][before_type] + s[day][after_type]
    
    bef_t = t[0:]
    aft_t = t[0:]
    aft_t[day] = after_type + 1

    l_day = {before_type: 0, after_type: 0}

    for day, type_ in enumerate(bef_t):
        day += 1
        type_ -= 1
        if type_  in l_day:
            l_day[type_] = day
        for c_type in l_day:
            diff += c[c_type] * (day - l_day[c_type])

    l_day = {before_type: 0, after_type: 0}
    for day, type_ in enumerate(aft_t):
        day += 1
        type_ -= 1
        if type_  in l_day:
            l_day[type_] = day
        for c_type in l_day:
            diff -= c[c_type] * (day - l_day[c_type])
    ans += diff
    t = aft_t[0:]
    print(ans)

Submission status: Time Limit Exceeded

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

MAX = 26

last = [0] * MAX

score = 0
for day, e in enumerate(t, 1):
    score += s[day-1][e-1]
    last[e-1] = day

    for ec, elast in zip(c, last):
        score -= ec * (day - elast)

for ed, eq in dq:
    q_old = t[ed-1]
    d_prev = {q_old: 0, eq: 0}

    c_old = c[q_old-1]
    c_new = c[eq-1]

    for day, e in enumerate(t, 1):
        if e in d_prev.keys():
            d_prev[e] = day

        score += c_old * (day - d_prev[q_old])
        score += c_new * (day - d_prev[eq])

    score -= s[ed-1][q_old-1]
    score += s[ed-1][eq-1]

    t[ed-1] = eq

    d_prev = {q_old: 0, eq: 0}

    for day, e in enumerate(t, 1):
        if e in d_prev.keys():
            d_prev[e] = day

        score -= c_old * (day - d_prev[q_old])
        score -= c_new * (day - d_prev[eq])

    print(score)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def calc_score(c, s, t, D):
    score = 0
    last = np.zeros((26, D), dtype=np.int16)
    for day, _t in enumerate(t):
        last[_t - 1, day:] = day + 1
        score += s[day, t[day] - 1]
    score -= (c * (np.arange(1, D + 1) - last).sum(axis=1)).sum()
    return score

D = int(input())
c = np.array(list(map(int, input().split())))
s = np.array([list(map(int, input().split())) for x in range(D)])
t = np.array([int(input()) for x in range(D)])
M = int(input())
q = np.array([list(map(int, input().split())) for x in range(M)])

for _q in q:
    t[_q[0] - 1] = _q[1]
    print(calc_score(c, s, t, D))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
import random
import time
start_time = time.time()
D = int(input())
c = [int(x) for x in input().split()]
s = []
for _ in range(D):
    s.append([int(x) for x in input().split()])

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

t = [int(input()) for _ in range(D)]
ans = solve(t)
m = int(input())
for _ in range(m):
    d, q = [int(x) for x in input().split()]
    temp = t[d - 1]
    t[d - 1] = q
    ans_2 = solve(t)
    ans = ans_2
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
d=int(input())


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

t=[int(input()) for _ in range(d)]
m=int(input())
change=[list(map(int,input().split())) for _ in range(m)]
ans=[]

for [dd,q] in change:
    last=[0]*26
    t[dd-1]=q
    #print(t)
    score=0
    for i in range(d):
        #print(i)
        score+=s[i][t[i]-1]
        last[t[i]-1]=i+1
        for j in range(26):
            score-=(c[j]*((i+1)-last[j]))
            
    ans.append(score)


for item in ans:
    print(item)

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

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

N = 26


def calc_score(t):
    scores = [0] * N
    last = [-1] * N
    for d in range(D):
        last[t[d]] = d
        scores[t[d]] += s[d][t[d]]

        for i in range(N):
            if last[t[d]] != -1:
                scores[i] -= c[i] * (d - last[i])
    return sum(scores)


for di, qi in zip(d, q):
    t[di] = qi
    print(calc_score(t))

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import accumulate
import bisect

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def main():
    D = ii()
    c = list(mi())
    s = [list(mi()) for i in range(D)]

    t = [ii()-1 for i in range(D)]

    M = ii()
    ans = [0]*M

    for j in range(M):
        d, q = mi()
        t[d-1] = q-1

        last = [[0]*26 for i in range(D)]
        v = 0

        for d in range(D):
            for i in range(26):
                if i == t[d]:
                    last[d][i] = d+1
                else:
                    last[d][i] = last[d-1][i]

            k = sum(c[i]*(d+1-last[d][i]) for i in range(26))
            v += s[d][t[d]] - k

        ans[j] = v 

    print(*ans, sep='\n')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(300000)
from collections import defaultdict

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI0(): return map(lambda s: int(s) - 1, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
def LMI0(): return list(map(lambda s: int(s) - 1, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


D = I()
C = LMI()
S = [LMI() for _ in range(D)]
T = [I() - 1 for _ in range(D)]
M = I()


def eval(T):
    last = defaultdict(int)
    ans = 0
    for d in range(D):
        ans += S[d][T[d]]
        last[T[d]] = d + 1
        for i in range(26):
            ans -= C[i] * (d + 1 - last[i])
    return ans

for d, q in [tuple(MI0()) for _ in range(M)]:
    T[d] = q
    print(eval(T))

Submission status: Time Limit Exceeded

Solution code:
from random import randint
import sys
input = sys.stdin.readline


def calc_score(D, C, S, T):
    """
    開催日程Tを受け取ってそこまでのスコアを返す
    """
    contest_last_opened = [0]*26  # コンテストiを前回開催した日
    score = 0
    for d, t in enumerate(T, start=1):
        get_score = S[d-1][t-1]
        score += get_score
        contest_last_opened[t-1] = d
        loss_score = 0
        for i in range(26):
            ld = contest_last_opened[i]
            loss_score += C[i]*(d-ld)
        score -= loss_score
    return score


def local_search():
    pass


def main(D, C, S):
    T = []
    for d in range(1, D+1):
        # d日目に一番満足度が高いコンテストを開催する 1-indexed
        # S[d-1]で最大のコンテストiを選ぶ　→ 0点！w
        # d日目にコンテストiを選んだ時に一番スコアが高くなるiを選ぶ
        today_score = calc_score(D, C, S, T + [1])
        today_contest = 1
        for i in range(2, 26 + 1):
            tmp_score = calc_score(D, C, S, T + [i])
            if today_score < tmp_score:
                today_score = tmp_score
                today_contest = i
        T.append(today_contest)
    return T


if __name__ == '__main__':
    D = int(input())
    C = [int(i) for i in input().split()]
    S = [[int(i) for i in input().split()] for j in range(D)]
    T = [int(input()) for i in range(D)]
    M = int(input())
    DQ = [[int(i) for i in input().split()] for j in range(M)]
    for d, q in DQ:
        T[d-1] = q
        print(calc_score(D, C, S, T))

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 main():
    D = int(input())
    c = list(map(int, input().split()))
    s = [list(map(int, input().split())) for _ in range(D)]
    t = [int(input()) for _ in range(D)]
    M = int(input())
    dq = [list(map(int, input().split())) for _ in range(M)]

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


def calc(s, c, t):
    d = [0] * 26

    ans = 0
    days = 0
    for tt in t:
        for i in range(26):
            d[i] += 1
        d[tt-1] = 0
        ans += s[days][tt-1]
        for i in range(26):
            ans -= d[i] * c[i]
        days += 1

    return ans


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    d = int(input())
    ci = list(map(int, input().split()))
    si = []
    for _ in range(d):
        si.append(list(map(int, input().split())))
    answers = [int(input()) for _ in range(d)]

    #print(d, ci, si, answers)

    num_que = int(input())
    que = []
    for _ in range(num_que):
        que.append(list(map(int, input().split())))
    #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)
        # 最終スコア
        print(score_now)
resolve()

Submission status: Time Limit Exceeded

Solution code:
def main():
    D = int(input())
    c_list = list(map(int, input().split()))
    s_list = [list(map(int, input().split())) for _ in range(D)]
    t_list = [int(input()) for _ in range(D)]

    #res_list = []
    M = int(input())
    for m in range(M):
        d,q = map(int, input().split())
        t_list[d-1] = q
        res = 0
        
        last_open = [0] * 26
        for i in range(D):
            t = t_list[i]
            res += s_list[i][t-1]

            # TODO: ここは毎回26ループ回す必要がないところになりうるので改善可能かも(なおすだけで20回分の処理が消せる)
            bad = 0
            last_open[t-1] = i+1
            for ci in range(26):
                bad += c_list[ci]*(i+1 - last_open[ci])

            res -= bad

        print(res)

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 = [int(input()) for i in range(d)]
now = [0]*26

score = [[0] for i in range(26)]
for i in range(d):
    
    now[t[i]-1] = i+1
    ind = t[i]-1
    for j in range(26):
        if j == ind:
            score[j].append(s[i][ind]+score[j][-1])
        else:
            x = (i+1-now[j])*c[j]
            score[j].append(-x+score[j][-1])
m = int(input())
l = [list(map(int,input().split())) for i in range(m)]

for i in range(m):
    x,y = l[i]
    be = t[x-1]
    be -= 1
    now = 0
    t[x-1] = y
    y -= 1
    count = [0]
    for j in range(d):
        if be == t[j]-1:
            now = j+1
            count.append(s[j][be]+count[-1])
        else:
            count.append(-(j+1-now)*c[be]+count[-1])
    score[be] = count
    count = [0]
    now = 0
    for j in range(d):
        if y == t[j]-1:
            now = j+1
            count.append(s[j][y]+count[-1])
        else:
            count.append(-(j+1-now)*c[y]+count[-1])
    score[y] = count

    ans = 0
    for i in range(26):
        ans += score[i][-1]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def calc_satisfaction():
    S = 0
    last = [0] * 27
    #score = 0
    for d in range(1, D + 1):
        S += s[d][t[d]]
        last[t[d]] = d
        for i in range(1, 27):
            S -= c[i] * (d - last[i])
        #score += max(10 ** 6 + S, 0)
    return S

D = int(input())
c = [None] + list(map(int, input().split()))
s = [None] + [[None] + list(map(int, input().split())) for _ in range(D)]
t = [None] + [int(input()) for _ in range(D)]
M = int(input())
for _ in range(M):
    d, q = map(int, input().split())
    old = t[d]
    t[d] = q
    print(calc_satisfaction())

Submission status: Time Limit Exceeded

Solution code:
from random import randint
from functools import lru_cache

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

@lru_cache(maxsize=10**5)
def score(d, ti, *last):
    s = sl[d-1][ti]
    for i in range(len(cl)):
        c = cl[i]
        s -= c*(d-last[i])
    return s

def scores(tl):
    s = 0
    last = [0]*26
    for d in range(D):
        t = tl[d] - 1
        last[t] = d+1
        s += score(d+1,t,*last)
    return s


for i in range(M):
    d,q = dq[i]
    x = tl[d-1]
    tl[d-1] = q
    print(scores(tl))

Submission status: Time Limit Exceeded

Solution code:
d=int(input())
c=list(map(int,input().split()))
s=[]
t=[]
for i in range(d):
    List=list(map(int,input().split()))
    s.append(List)
for i in range(d):
    t_d=int(input())
    t.append(t_d)
m=int(input())
for i in range(m):
    new_t=t
    ans=0
    last=[0]*26
    order=list(map(int,input().split()))
    new_t[order[0]-1]=order[1]
    for i in range(1,d+1):
        ans+=s[i-1][new_t[i-1]-1]
        last[new_t[i-1]-1]=i
        for j in range(1,27):
            ans-=c[j-1]*(i-last[j-1])
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
d = int(input())
c_li = list(map(int, input().split()))
s_li = [list(map(int, input().split())) for _ in range(d)]
t_li = [int(input()) for _ in range(d)]
m = int(input())
m_li = [list(map(int, input().split())) for _ in range(m)]


for k in range(m):
    ans = 0
    last_d = [-1] * 26
    t_li[m_li[k][0]-1] = m_li[k][1]
    for i in range(d):
        op = t_li[i] - 1
        ans += s_li[i][op]
        last_d[op] = i
        for j in range(26):
            ans -= c_li[j] * (i-last_d[j])
        
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left as bl 
D=int(input())
C=list(map(int,input().split()))
S=[list(map(int,input().split())) for _ in range(D)]
T=[int(input()) for _ in range(D)]
M=int(input())
DQ=[list(map(int,input().split())) for _ in range(M)]

last=[[0] for _ in range(26)]
score=[0]*D
for i in range(D):
    contest=T[i]-1
    if i == 0:
        score[i]=S[i][contest]
    else:
        score[i]=score[i-1]+S[i][contest]
    last[contest].append(i+1)
    for j in range(26):
        blank=i+1-last[j][-1]
        score[i]-=blank*C[j]

def research(day,query):
    global last,T,score,C
    T[day-1]=query
    for i in range(26):
        ind=bl(last[i],day)
        last[i]=last[i][:ind]

    for i in range(day-1,D):
        contest=T[i]-1
        if i == 0:
            score[i]=S[i][contest]
        else:
            score[i]=score[i-1]+S[i][contest]
        last[contest].append(i+1)
        for j in range(26):
            blank=i+1-last[j][-1]
            score[i]-=blank*C[j]
    return

for i in range(M):
    d,q=DQ[i][0],DQ[i][1]
    research(d,q)
    print(score[-1])

Submission status: Time Limit Exceeded

Solution code:
D=int(input())                                          #コンテの日数
c=list(map(int,input().split()))                        #26タイプ(AAC~AZC)のコンテストの満足度低下度
s=[list(map(int,input().split())) for _ in range(D)]    #s[d][i]...d(1<=d<=D)日目にi(1<=i<=26)番目のコンテストを行った時の満足度上昇
types=[int(input()) for _ in range(D)]                  #コンテタイプ(1~26)
M=int(input())                                          #日程変更クエリ回数
datefromto=[list(map(int,input().split())) for _ in range(M)]       #各クエリの変更内容
#満足度低下はΣ(1<=i<=26)ci*(d-last(d,i))                  #なおlast(d,i)=d日目以前に最後にタイプiのコンテストをやった日にち(ない場合0)
#よって満足度はs[d][i]-Σ(1<=i<=26)ci*(d-last(d,i))
#i日目のスコアはmax(10^6+s[d][i]-Σ(1<=i<=26)ci*(d-last(d,i)),0)                                             #typeごとに、最後に使われた日にちを記録するよ
typ=0
for le in range(M):
    d,q=datefromto[le]
    types[d-1]=q
    ans=0
    last = [0] * 26
    #print(types)
    for i in range(D):
        typ=types[i]-1
        score=s[i][typ]
        dwn=0
        last[typ]=(i+1)
        for j in range(26):
            dwn=dwn+c[j]*((i+1)-last[j])
        ans=ans+(score-dwn)
        #print(score,last)
    print(ans)
    #input()

Submission status: Time Limit Exceeded

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

s=[None]*D
for i in range(D):
    s[i] = list(map(int,input().split()))
t=[0]*D
for i in range(D):
    t[i]=int(input())
    
m=int(input())
d=[None]*m
q=[None]*m
for i in range(m):
    d[i],q[i] = map(int,input().split())

def calc_score(t):
    last=[0]*26
    satis=0
    pena=0
    for j in range(D):
        ss=s[j]
        tt=t[j]
        satis += ss[tt-1]
        last[tt-1]=j+1
        
        pena += sum(c[i]*(j+1-last[i]) for i in range(26))
    return satis-pena

# calc_score(t)-10**6
for i in range(m):
    t[d[i]-1] = q[i]
    print(calc_score(t))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def calc_score(c, s, t, D):
    score = 0
    last = np.zeros(26, dtype=np.int16)
    for day in range(1, D + 1):
        score += s[day - 1, t[day - 1] - 1]
        last[t[day - 1] - 1] = day
        score -= (c * (day - last)).sum()
    return score

D = int(input())
c = np.array(list(map(int, input().split())))
s = np.array([list(map(int, input().split())) for x in range(D)])
t = np.array([int(input()) for x in range(D)])
M = int(input())
q = np.array([list(map(int, input().split())) for x in range(M)])

for _q in q:
    t[_q[0] - 1] = _q[1]
    print(calc_score(c, s, t, D))

Submission status: Time Limit Exceeded

Solution code:
D=int(input())
c=input().split()
c=[int(a) for a in c]
S=[]
for _ in range(D):
    s=input().split()
    s=[int(a) for a in s]
    S.append(s)
T=[]
for _ in range(D):
    t=int(input())-1
    T.append(t)
M=int(input())
numbers=[]
for _ in range(M):
    d,q=map(int,input().split())
    numbers.append([d,q])
for m in range(M):
    ans = 0
    held = [0 for _ in range(26)]
    e=numbers[m][0]-1
    q=numbers[m][1]-1
    a=T[e]
    T[e]=q
    for d in range(D):
        s = S[d]
        place = T[d]
        held[place] = d + 1
        ans += s[place]
        for n in range(26):
            ans -= c[n] * (d + 1 - held[n])
    print(ans)

Submission status: Time Limit Exceeded

Solution code:

D = int(input())
c_list = list(map(int, input().split()))
s_list = [list(map(int, input().split())) for _ in range(D)]
t_list = [int(input()) for _ in range(D)]


#res_list = []
M = int(input())
for m in range(M):
    d,q = map(int, input().split())
    t_list[d-1] = q
    res = 0
    
    last_open = [0] * 26
    for i in range(D):
        t = t_list[i]
        res += s_list[i][t-1]

        bad = 0
        last_open[t-1] = i+1
        for ci in range(26):
            bad += c_list[ci]*(i+1 - last_open[ci])

        res -= bad

    print(res)
    #res_list.append(res)
#print(res_list)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
C = list(map(int,input().split())) #C[i]AiCを実施しないと下がる満足度
S = [] #S[i][j] i日目にAjcというコンテストを実施した場合に上がる満足度
for i in range(D): #コンテストは0index
    temp = list(map(int,input().split()))
    S.append(temp)
T = []
for i in range(D):
    temp = int(input())
    T.append(temp)
M = int(input())
DQ = []
for i in range(M):
    d,q = map(int,input().split())
    DQ.append((d,q))
#since = [0 for _ in range(26)] #最後に開催されてから何日経ったか。
#manzoku = 0
def cycle(T):
    manzoku = 0
    since = [0 for _ in range(26)]
    for i in range(26):
        since[i] += C[i]
    for i in range(D):
        contest = T[i]-1 #0index
        manzoku += S[i][contest]
        for j in range(26):
            if j != contest:
                manzoku -= since[j]
        #print(manzoku)
        for j in range(26):
            if j != contest:
                since[j] += C[j]
            else:
                since[j] = C[j]
    return manzoku
score = cycle(T)
for i in range(M):
    d,q = DQ[i]
    d-=1 #0indexへ
    old = T[d]
    T[d] = q
    nscore = cycle(T)
    print(nscore)
    #if nscore >= score:
    #    print(nscore)
    #else:
    #    print(score)
    #    T[d] = old

Submission status: Time Limit Exceeded

Solution code:
def sumDesire(C, d, last):
    sumA = 0
    for i in range(26):
        sumA += C[i] * (d - last[i])
    return sumA


def solve(D, C, SD, T):
    from collections import defaultdict
    last = defaultdict(int)
    ans = 0
    for i in range(D):
        ans += SD[i][T[i] - 1]
        last[T[i] - 1] = i + 1
        ans -= sumDesire(C, i + 1, last)
    return ans


def resolve():
    D = int(input())
    C = [int(i) for i in input().split()]
    SD = [list(map(int, input().split())) for _ in range(D)]
    T = [int(input()) for _ in range(D)]
    M = int(input())
    ddqq = [list(map(int, input().split())) for _ in range(M)]

    # solve(D, C, SD, T)

    for i in range(M):
        d, q = ddqq[i]
        T[d - 1] = q
        print(solve(D, C, SD, T))


resolve()

Submission status: Time Limit Exceeded

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

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

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

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

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