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


#last=[[0]]*26

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

M=int(input())

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

Submission status: Time Limit Exceeded

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** -10

D = INT()
C = LIST()
S = [[]] * D
for i in range(D):
    S[i]  = LIST()
T = [t-1 for t in LIST(D)]
M = 26

def check(T):
    last = [0] * M
    res = 0
    for i, t in enumerate(T):
        res += S[i][t]
        for j in range(M):
            last[j] += 1
        last[t] = 0
        for j in range(M):
            res -= C[j] * last[j]
    return res

Q = INT()
for i in range(Q):
    d, q = MAP()
    d -= 1; q -= 1

    T[d] = q
    res = check(T)
    print(res)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import random
import sys
input = sys.stdin.readline

def last(p, k):
    x = bisect.bisect_right(last_hol[k], p,)
    if x == 0:
        return 0
    else:
        return last_hol[k][x - 1]


def score(t_in):
    ans = 0
    for i in range(d):
        ti = t_in[i]
        ans += s[i][ti - 1]
        for j in range(1, 27):
            ans -= c[j - 1] * (i + 1 - last(i + 1, j))
    return ans


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)]
last_hol = {i: [] for i in range(1, 27)}
for i in range(d):
    ti = t[i]
    last_hol[ti].append(i + 1)
v = []
for i in range(int(input())):
    a, b = map(int, input().split())
    t[a - 1] = b
    last_hol = {i: [] for i in range(1, 27)}
    for i in range(d):
        ti = t[i]
        last_hol[ti].append(i + 1)
    v.append(score(t))

for vi in v:
    print(vi)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
D=int(input())
*c,=map(int,input().split())
s=[]
for i in range(D):
    *x,=map(int,input().split())
    s.append(x)
T=[]
for i in range(D):
    T.append(int(input()))

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

m=int(input())
for i in range(m):
    d,q=map(int,input().split())
    T[d-1]=q
    print(score(T))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

def last(d):
    l=np.zeros(26,int)
    for i in range(d):
        l[T[i]-1]=i+1
    return l

def decrease(d):
    return np.dot(C,(d-last(d)))


def manzoku():
    inc=[S[i][T[i]-1] for i in range(D)]
    dec=[decrease(i+1) for i in range(D)] 
    return inc,dec

def change(d,q):
    T[d-1]=q
    inc[d-1]=S[d-1][T[d-1]-1]
    for i in range(d-1,D):
        dec[i]=decrease(i+1)

inc,dec=manzoku()

M=int(input())
for m in range(M):
    d,q=map(int,input().split())
    change(d,q)
#     print(inc)
#     print(dec)
    
    print(sum(inc)-sum(dec))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

def last(d):
    l=np.zeros(26,int)
    for i in range(d):
        l[T[i]-1]=i+1
    return l

def decrease(d):
    return np.dot(C,(d-last(d)))


def manzoku():
    manzoku=0
    for i in range(D):
        manzoku+=S[i][T[i]-1]
        manzoku-=decrease(i+1)
    return manzoku




M=int(input())
for m in range(M):
    d,q=map(int,input().split())
    T[d-1]=q
    print(manzoku())

Submission status: Time Limit Exceeded

Solution code:
d=int(input())
c=list(map(int,input().split()))
num=[]
for i in range(d):
    num.append(list(map(int,input().split())))
t=[]
for i in range(d):
    t.append(int(input()))
m=int(input())
ans1=[]
for i in range(m):
    ans=0
    num2=[0]*26
    a,q=map(int,input().split())
    t[a-1]=q
    for j in range(1,d+1):
        num2[t[j-1]-1]=j
        ans+=num[j-1][t[j-1]-1]
        for k in range(26):
            ans-=((j-num2[k])*c[k])
    ans1.append(ans)
for i in range(m):
    print(ans1[i])

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
c = [int(i) for i in input().split()]
s = [[int(i) for i in input().split()] for _ in range(D)]
t = [int(input())-1 for _ in range(D)]

def calc(x):
    res = 0
    last = 0
    for day,i in enumerate(range(D),1):
        if t[i] == x:
            last = day
            res += s[i][x]
        res -= c[x]*(day-last)
    return res

score = [0]*26
for i in range(26): score[i] = calc(i)
M = int(input())
ans = [0]*M
for i in range(M):
    d,q = map(int,input().split())
    d -= 1
    q -= 1
    old = t[d]
    t[d] = q
    score[old] = calc(old)
    score[q] = calc(q)
    ans[i] = sum(score)
for i in range(M): print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
c = [int(i) for i in input().split()]
s = [[int(i) for i in input().split()] for _ in range(D)]
t = [int(input())-1 for _ in range(D)]

def calc(x):
    res = 0
    last = 0
    for day,i in enumerate(range(D),1):
        if t[i] == x:
            last = day
            res += s[i][x]
        res -= c[x]*(day-last)
    return res

score = [0]*26
for i in range(26): score[i] = calc(i)
M = int(input())
ans = [0]*M
for i in range(M):
    d,q = map(int,input().split())
    d -= 1
    q -= 1
    old = t[d]
    t[d] = q
    score[old] = calc(old)
    score[q] = calc(q)
    ans[i] = sum(score)
for i in range(M): print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
D = int(input())
c = [int(i) for i in input().split()]
s = [[int(i) for i in input().split()] for _ in range(D)]
t = [int(input())-1 for _ in range(D)]
llst = [0]*26

def scoreing():
    res = 0
    for i in range(26): llst[i] = 0
    for day,i in enumerate(range(D),1):
        llst[t[i]] = day
        res += s[i][t[i]]
        for j in range(26): res -= c[j]*(day-llst[j])
    return res
        
M = int(input())
ans = [0]*M
for i in range(M):
    d,q = map(int,input().split())
    d -= 1
    q -= 1
    t[d] = q
    ans[i] = scoreing()
for i in range(M): print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
input=lambda :sys.stdin.readline().rstrip()

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

def calc_score(T):
    last = [0] * 26
    score = 0
    for d in range(D):
        v = T[d]
        score += S[d][v]
        for i in range(26):
            if i == v: last[i] = 0
            else: last[i] += 1
            score -= C[i] * last[i]
        # print(score)
    return score

m = int(input())
DQ = [tuple(map(int, input().split())) for _ in range(m)]
DQ = [(p - 1, q - 1) for p, q in DQ]
for d, q in DQ:
    T[d] = q
    print(calc_score(T))

Submission status: Time Limit Exceeded

Solution code:
import sys
input=lambda :sys.stdin.readline().rstrip()

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

def calc_score(T):
    last = [0] * 26
    score = 0
    for d in range(D):
        v = T[d]
        score += S[d][v]
        for i in range(26):
            if i == v: last[i] = 0
            else: last[i] += 1
            score -= C[i] * last[i]
        # print(score)
    return score

m = int(input())
DQ = [tuple(map(int, input().split())) for _ in range(m)]
for d, q in DQ:
    T[d-1] = q-1
    print(calc_score(T))

Submission status: Time Limit Exceeded

Solution code:
import sys
input=lambda :sys.stdin.readline().rstrip()

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

def calc_score(T):
    last = [0] * 26
    score = 0
    for d in range(D):
        v = T[d]
        score += S[d][v]
        for i in range(26):
            if i == v:
                last[i] = 0
            else:
                last[i] += 1
            score -= C[i] * last[i]
        # print(score)
    return score

m = int(input())
DQ = [list(map(int, input().split())) for _ in range(m)]
for d, q in DQ:
    d -= 1
    q -= 1
    T[d] = q
    new_score = calc_score(T)
    print(new_score)

Submission status: Time Limit Exceeded

Solution code:
#Thanks for https://atcoder.jp/contests/intro-heuristics/submissions/14809214

import sys
input=lambda :sys.stdin.readline().rstrip()

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

def calc_score(T):
    last = [0] * 26
    score = 0
    for d in range(D):
        v = T[d]
        score += S[d][v]
        for i in range(26):
            if i == v:
                last[i] = 0
            else:
                last[i] += 1
            score -= C[i] * last[i]
        # print(score)
    return score

m = int(input())
DQ = [tuple(map(int, input().split())) for _ in range(m)]
for d, q in DQ:
    d -= 1 
    q -= 1
    T[d] = q
    new_score = calc_score(T)
    print(new_score)

Submission status: Time Limit Exceeded

Solution code:
#Thanks for https://atcoder.jp/contests/intro-heuristics/submissions/14809214

import sys
input=lambda :sys.stdin.readline().rstrip()

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

def calc_score(T):
    last = [0] * 26
    score = 0
    for d in range(D):
        v = T[d]
        score += S[d][v]
        for i in range(26):
            if i == v:
                last[i] = 0
            else:
                last[i] += 1
            score -= C[i] * last[i]
        # print(score)
    return score

m = int(input())
DQ = [list(map(int, input().split())) for _ in range(m)]
for d, q in DQ:
    d -= 1
    q -= 1
    old = T[d]
    T[d] = q
    new_score = calc_score(T)
    print(new_score)

Submission status: Time Limit Exceeded

Solution code:
#Thanks for https://atcoder.jp/contests/intro-heuristics/submissions/14809214

import sys
input=lambda :sys.stdin.readline().rstrip()

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

def calc_score(T):
    last = [0] * 26
    score = 0
    for d in range(D):
        v = T[d]
        score += S[d][v]
        for i in range(26):
            if i == v:
                last[i] = 0
            else:
                last[i] += 1
            score -= C[i] * last[i]
        # print(score)
    return score

m = int(input())
for _ in range(m):
    d, q = map(int, input().split())
    d -= 1
    q -= 1
    old = T[d]
    T[d] = q
    new_score = calc_score(T)
    print(new_score)

Submission status: Time Limit Exceeded

Solution code:
#Thanks for https://atcoder.jp/contests/intro-heuristics/submissions/14809214

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

def calc_score(T):
    last = [0] * 26
    score = 0
    for d in range(D):
        v = T[d]
        score += S[d][v]
        for i in range(26):
            if i == v:
                last[i] = 0
            else:
                last[i] += 1
            score -= C[i] * last[i]
        # print(score)
    return score

m = int(input())
for _ in range(m):
    d, q = map(int, input().split())
    d -= 1
    q -= 1
    old = T[d]
    T[d] = q
    new_score = calc_score(T)
    print(new_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)

DAYS = list(range(1, D + 1))
KIND = 26


def get_last() -> np.ndarray:
    last = np.zeros(shape=(D, KIND))
    for day in DAYS:
        index_day = day - 1
        if day != 1:
            last[index_day] = last[index_day - 1]
        t_day = t[index_day]
        index_tday = t_day - 1
        last[index_day][index_tday] = day

    return last


def cost(t: np.ndarray, last: np.ndarray) -> int:
    S = 0
    for day in DAYS:
        index_day = day - 1
        index_tday = t[index_day] - 1
        S += s[index_day][index_tday]
        S -= c.dot(day - last[index_day])
    return int(S)


def main() -> None:
    # 求解処理
    last = get_last()
    S = cost(t, last)
    for d_m, q_m in zip(d, q):
        index_dm = d_m - 1
        t_dm = t[index_dm]
        index_tdm = t_dm - 1
        index_qm = q_m - 1

        S = S - s[index_dm][index_tdm] + s[index_dm][index_qm]

        last_T = last.T

        c_tdm = c[index_tdm]
        c_tdm_array = np.full(shape=D, fill_value=c_tdm)
        last_T_tdm = last_T[index_tdm]
        S += c_tdm_array.dot(DAYS - last_T_tdm)
        last_T_tdm = np.where(last_T_tdm == d_m,
                              last_T_tdm[index_dm - 1] if index_dm != 0 else 0,
                              last_T_tdm)
        last_T[index_tdm] = last_T_tdm
        S -= c_tdm_array.dot(DAYS - last_T_tdm)

        c_qm = c[index_qm]
        c_qm_array = np.full(shape=D, fill_value=c_qm)
        last_T_qm = last_T[index_qm]
        S += c_qm_array.dot(DAYS - last_T_qm)
        last_T_qm_sub = last_T_qm[index_dm:]
        last_T_qm_sub = np.where(last_T_qm_sub == last_T_qm[index_dm],
                                 d_m,
                                 last_T_qm_sub)
        last_T_qm[index_dm:] = last_T_qm_sub
        last_T[index_qm] = last_T_qm
        S -= c_qm_array.dot(DAYS - last_T_qm)
        last = last_T.T
        t[index_dm] = q_m

        print(int(S))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
""" 局所探索の例 """
import numpy as np
import sys

input = sys.stdin.readline


contest_types = 26
days = int(input())
cs = list(map(int, input().strip().split()))
ss = [list(map(int, input().strip().split())) for _ in range(days)]
ts = [int(input()) - 1 for _ in range(days)] # 0 始まりにする

m = int(input())
queries = [list(map(int, input().strip().split())) for _ in range(m)]
queries = np.array(queries, dtype=np.int32)
queries -= 1  # 0始まりにする

# コンテストごとの開催日
def calc_contest_dict(ts):
    contest_dict = [[-1, days] for _ in range(contest_types)]
    for d, t in enumerate(ts):
        contest_dict[t].append(d)

    for contest_days in contest_dict:
        contest_days.sort()

    return contest_dict

def count_block(contest_days):
    block = 0
    for i in range(len(contest_days) - 1):
        period = contest_days[i + 1] - contest_days[i]
        block += period * (period - 1) // 2
    return block


def calc_score(cs, ss, ts):
    contest_dict = calc_contest_dict(ts)
    # 満足度
    satisfaction = 0
    # 開催されることによる増加分
    for d, t in enumerate(ts):
        satisfaction += ss[d][t]

    # 減少分
    for t, contest_days in enumerate(contest_dict):
        decrease = cs[t] * count_block(contest_days)
        satisfaction -= decrease

    return satisfaction


score = calc_score(cs, ss, ts)
contest_dict = calc_contest_dict(ts)
for d, q in queries:
    old_t = ts[d]
    new_t = q
    old_decrease = cs[old_t] * count_block(contest_dict[old_t]) \
                 + cs[new_t] * count_block(contest_dict[new_t])
    ts[d] = new_t
    contest_dict = calc_contest_dict(ts)
    open_diff = ss[d][new_t] - ss[d][old_t]

    new_decrease = cs[old_t] * count_block(contest_dict[old_t]) \
                 + cs[new_t] * count_block(contest_dict[new_t])

    diff = open_diff + old_decrease - new_decrease
    score += diff
    print(score)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

d = int(input())
*C, = map(int, input().split())
S = [list(map(int, input().split())) for i in range(d)]
T = [int(input()) - 1 for i in range(d)]
L = [[-1]]


def score(T):
    L = [-1 for j in range(26)]
    tmp = 0
    for i in range(d):
        tmp += S[i][T[i]]
        L[T[i]] = i
        tmp -= sum([C[j] * (i - L[j]) for j in range(26)])
    return tmp


m = int(input())
for k in range(m):
    p, q = map(int, input().split())
    T[p - 1] = q - 1
    print(score(T))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
#d=日数, c=満足低下度, s=満足上昇度, t=コンテストの日程 
d = int(stdin.readline().rstrip())
c = list(map(int, stdin.readline().rstrip().split()))
#print(c)
s = [list(map(int, stdin.readline().rstrip().split())) for i in range(d)]
t = [int(stdin.readline().rstrip()) for j in range(d)]
m = int(stdin.readline().rstrip())
#dq = [list(map(int, input().split())) for i in range(m)]
for j in range(m):
  dq = list(map(int, stdin.readline().rstrip().split()))
  res = 0
  last = [0 for i in range(26)]
  #old = t[dq[j][0] - 1]
  t[dq[0] - 1] = dq[1]
  for day in range(d):
    res += s[day][t[day]-1]
    last[t[day]-1] = day+1
    #for i in range(26):
      #res -= c[i] * (day + 1 - last[i])
    combined1 = [x * (day + 1 - y) for (x, y) in zip(c, last)]
    res -= sum(combined1)
  #t[dq[j][0] - 1] = old
  print(res)

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)

# 求解処理
DAYS = list(range(1, D + 1))
KIND = 26
last = np.zeros(shape=(D, KIND))
for day in DAYS:
    index_day = day - 1
    if day != 1:
        last[index_day] = last[index_day - 1]
    t_day = t[index_day]
    index_tday = t_day - 1
    last[index_day][index_tday] = day


def cost(t: np.ndarray, last: np.ndarray) -> int:
    S = 0
    for day in DAYS:
        index_day = day - 1
        index_tday = t[index_day] - 1
        S += s[index_day][index_tday]
        S -= c.dot(day - last[index_day])
    return int(S)


S = cost(t, last)
for d_m, q_m in zip(d, q):
    index_dm = d_m - 1
    t_dm = t[index_dm]
    index_tdm = t_dm - 1
    index_qm = q_m - 1

    S = S - s[index_dm][index_tdm] + s[index_dm][index_qm]

    last_T = last.T

    c_tdm = c[index_tdm]
    c_tdm_array = np.full(shape=D, fill_value=c_tdm)
    last_T_tdm = last_T[index_tdm]
    S += c_tdm_array.dot(DAYS - last_T_tdm)
    last_T_tdm = np.where(last_T_tdm == d_m,
                          last_T_tdm[index_dm - 1] if index_dm != 0 else 0,
                          last_T_tdm)
    last_T[index_tdm] = last_T_tdm
    S -= c_tdm_array.dot(DAYS - last_T_tdm)

    c_qm = c[index_qm]
    c_qm_array = np.full(shape=D, fill_value=c_qm)
    last_T_qm = last_T[index_qm]
    S += c_qm_array.dot(DAYS - last_T_qm)
    last_T_qm_sub = last_T_qm[index_dm:]
    last_T_qm_sub = np.where(last_T_qm_sub == last_T_qm[index_dm],
                             d_m,
                             last_T_qm_sub)
    last_T_qm[index_dm:] = last_T_qm_sub
    last_T[index_qm] = last_T_qm
    S -= c_qm_array.dot(DAYS - last_T_qm)
    last = last_T.T
    t[index_dm] = q_m

    print(int(S))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
#d=日数, c=満足低下度, s=満足上昇度, t=コンテストの日程 
d = int(stdin.readline().rstrip())
c = list(map(int, stdin.readline().rstrip().split()))
#print(c)
s = [list(map(int, stdin.readline().rstrip().split())) for i in range(d)]
t = [int(stdin.readline().rstrip()) for j in range(d)]
m = int(stdin.readline().rstrip())
#dq = [list(map(int, input().split())) for i in range(m)]
for j in range(m):
  dq = list(map(int, stdin.readline().rstrip().split()))
  res = 0
  last = [0 for i in range(26)]
  #old = t[dq[j][0] - 1]
  t[dq[0] - 1] = dq[1]
  for day in range(d):
    res += s[day][t[day]-1]
    last[t[day]-1] = day+1
    #for i in range(26):
      #res -= c[i] * (day + 1 - last[i])
    combined1 = [x * (day + 1 - y) for (x, y) in zip(c, last)]
    res -= sum(combined1)
  #t[dq[j][0] - 1] = old
  print(res)

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)

# 求解処理
DAYS = list(range(1, D + 1))
KIND = 26
last = np.zeros(shape=(D, KIND))
for day in DAYS:
    index_day = day - 1
    if day != 1:
        last[index_day] = last[index_day - 1]
    t_day = t[index_day]
    index_tday = t_day - 1
    last[index_day][index_tday] = day


def cost(t: np.ndarray, last: np.ndarray) -> int:
    S = 0
    for day in DAYS:
        index_day = day - 1
        index_tday = t[index_day] - 1
        S += s[index_day][index_tday]
        S -= c.dot(day - last[index_day])
    return int(S)


S = cost(t, last)
for d_m, q_m in zip(d, q):
    index_dm = d_m - 1
    t_dm = t[index_dm]
    index_tdm = t_dm - 1
    index_qm = q_m - 1

    S = S - s[index_dm][index_tdm] + s[index_dm][index_qm]

    last_T = last.T

    t_dm_array = np.full(shape=D, fill_value=t_dm)
    last_T_tdm = last_T[index_tdm]
    S += t_dm_array.dot(DAYS - last_T_tdm)
    last_T_tdm = np.where(last_T_tdm == d_m,
                          last_T_tdm[index_dm - 1] if index_dm != 0 else 0,
                          last_T_tdm)
    last_T[index_tdm] = last_T_tdm
    S -= t_dm_array.dot(DAYS - last_T_tdm)

    q_m_array = np.full(shape=D, fill_value=q_m)
    last_T_qm = last_T[index_qm]
    S += q_m_array.dot(DAYS - last_T_qm)
    last_T_qm_sub = last_T_qm[index_dm:]
    last_T_qm_sub = np.where(last_T_qm_sub == last_T_qm[index_dm],
                             d_m,
                             last_T_qm_sub)
    last_T_qm[index_dm:] = last_T_qm_sub
    last_T[index_qm] = last_T_qm
    S -= q_m_array.dot(DAYS - last_T_qm)
    last = last_T.T
    t[index_dm] = q_m

    print(cost(t, last))

Submission status: Time Limit Exceeded

Solution code:
d = int(input())
*C, = map(int, input().split())
S = [list(map(int, input().split())) for i in range(d)]
T = [int(input()) - 1 for i in range(d)]


def score(T):
    L = [-1 for j in range(26)]
    tmp = 0
    for i in range(d):
        tmp += S[i][T[i]]
        L[T[i]] = i
        tmp -= sum([C[j] * (i - L[j]) for j in range(26)])
    return tmp


m = int(input())
for k in range(m):
    p, q = map(int, input().split())
    T[p - 1] = q - 1
    print(score(T))