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

Solution code:
def calcScore():
    for d in range(1, D + 1):
        id = t[d]  # この日に開催するコンテスト
        sinceLast[d][id] = 0
        score[d][id] = s[d][id]


        for i in range(1, 26 + 1):
            if i == id:  continue
            sinceLast[d][i] = sinceLast[d - 1][i] + 1
            score[d][i] = -c[i] * sinceLast[d][i]

    ans = 0
    for d in range(1, D + 1):
        ans += sum(score[d])

    return ans

def calcScoreDiff(score, d, before, after):
    ans = 0
    for dd in range(d, D + 1):
        if dd > d and t[dd] == before:  break
        sinceLast[dd][before] = sinceLast[dd - 1][before] + 1
        ans -= score[dd][before]
        score[dd][before] = -c[before] * sinceLast[dd][before]
        ans += score[dd][before]

    ans -= score[d][after]
    sinceLast[d][after] = 0
    score[d][after] = s[d][after]
    ans += score[d][after]

    for dd in range(d + 1, D + 1):
        if t[dd] == after:  break
        sinceLast[dd][after] = sinceLast[dd - 1][after] + 1
        ans -= score[dd][after]
        score[dd][after] = -c[after] * sinceLast[dd][after]
        ans += score[dd][after]

    return ans

D = int(input())
c = [0] + [int(x) for x in input().split()]
s = [[0 for _ in range(26 + 1)]] + \
    [[0] + [int(x) for x in input().split()] for _ in range(D)]
t = [0] + [int(input()) for _ in range(D)]

score = [[0] * (26 + 1) for _ in range(D + 1)]
sinceLast = [[0] * (26 + 1) for _ in range(D + 1)]
tot = calcScore()

M = int(input())
for i in range(M):
    d, after = [int(x) for x in input().split()]
    before = t[d]
    t[d] = after
    diff = calcScoreDiff(score, d, before, after)
    tot += diff
    print(tot)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

def calcScore(t, s, c):
    scores = [0]*26
    lasts = [0]*26
    for i in range(1, len(t)):
        scores[t[i]] += s[i][t[i]]
        dif = i - lasts[t[i]]
        scores[t[i]] -= c[t[i]] * dif * (dif-1) // 2
        lasts[t[i]] = i
    for i in range(26):
        dif = len(t) - lasts[i]
        scores[i] -= c[i] * dif * (dif-1) // 2
    return scores

def update(socre, day, t, q):
    p = t[day]
    t[day] = q
    scores[p] = 0
    scores[q] = 0
    lasts = [0]*26
    for i in range(1, len(t)):
        if t[i] == p or t[i] == q:
            scores[t[i]] += s[i][t[i]]
            dif = i - lasts[t[i]]
            scores[t[i]] -= c[t[i]] * dif * (dif-1) // 2
            lasts[t[i]] = i
    for i in [p, q]:
        dif = len(t) - lasts[i]
        scores[i] -= c[i] * dif * (dif-1) // 2
    return scores

D = int(input())
c = list(map(int, input().split()))
s = [[0]*26 for _ in range(D+1)]
for i in range(1, D+1):
    s[i] = list(map(int, input().split()))
t = [-1]*(D+1)
for i in range(1, D+1):
    t[i] = int(input()) - 1
M = int(input())

scores = calcScore(t, s, c)

ans = [None]*M
for i in range(M):
    d, q = map(int, input().split())
    t[d] = q-1
    ans[i] = sum(calcScore(t, s, c))

for v in ans:
    print(v)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

def calcScore(t, s, c):
    scores = [0]*26
    lasts = [0]*26
    for i in range(1, len(t)):
        scores[t[i]] += s[i][t[i]]
        dif = i - lasts[t[i]]
        scores[t[i]] -= c[t[i]] * dif * (dif-1) // 2
        lasts[t[i]] = i
    for i in range(26):
        dif = len(t) - lasts[i]
        scores[i] -= c[i] * dif * (dif-1) // 2
    return scores

D = int(input())
c = list(map(int, input().split()))
s = [[0]*26 for _ in range(D+1)]
for i in range(1, D+1):
    s[i] = list(map(int, input().split()))
t = [-1]*(D+1)
for i in range(1, D+1):
    t[i] = int(input()) - 1
M = int(input())

scores = calcScore(t, s, c)

ans = [None]*M
for i in range(M):
    d, q = map(int, input().split())
    t[d] = q-1
    ans[i] = sum(calcScore(t, s, c))

for v in ans:
    print(v)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import numpy as np
from numba import njit


def read():
    D = int(input().strip())
    # C[i]: コンテストiの低下量にかかる係数
    C = np.fromstring(input().strip(), dtype=np.int32, sep=" ")
    # S[d, i]: d日目にコンテストiを開催したときの増加量
    S = np.empty((D, 26), dtype=np.int32)
    for i in range(D):
        s = np.fromstring(input().strip(), dtype=np.int32, sep=" ")
        S[i, :] = s[:]
    # T[d]: d日目に開催されるコンテストの種類
    T = np.array([int(input().strip()) for i in range(D)], dtype=np.int32)
    T -= 1
    # M: 変更クエリの数
    M = int(input().strip())
    # DQ[i]: d[i] 日目のコンテストを q[i] に変更する
    DQ = np.empty((M, 2), dtype=np.int32)
    for i in range(M):
        dq = np.fromstring(input().strip(), dtype=np.int32, sep=" ")
        DQ[i, :] = dq[:]
    DQ -= 1
    return D, C, S, T, M, DQ


@njit
def satisfaction(d, C, S, T, last):
    """満足度の変化を求める
    """
    v = 0
    # 増加分: S[d, i]
    p = T[d]
    v += S[d, p]
    last[p] = d
    # 低下分: sum(C[i] * (d-last[d, i]))
    for i in range(26):
        v -= C[i] * (d - last[i])
    return v


@njit
def change_schedule(D, C, S, T, d, q, cumsat):
    """d日目のコンテストをqに変更する
    """
    p = T[d]
    dp1, dq1 = -1, -1
    dp3, dq3 = D, D
    for i in range(0, d):
        if T[i] == p: 
            dp1 = i
        if T[i] == q:
            dq1 = i
    for i in range(D-1, d, -1):
        if T[i] == p:
            dp3 = i
        if T[i] == q:
            dq3 = i
    cumsat = cumsat - S[d, p] + S[d, q] - C[p] * (dp3-d) * (d-dp1) + C[q] * (dq3-d) * (d-dq1)
    return cumsat

@njit
def solve(D, C, S, T, M, DQ):
    # 最後にコンテストiを開催した日、未開催ならlast[i] = 0
    last = -np.ones(26, dtype=np.int32)
    # cumsat: d日目の満足度
    cumsat = 0
    # sat: d日目の満足度の増加量
    for d in range(D):
        sat = satisfaction(d, C, S, T, last)
        cumsat += sat
    for i in range(M):
        d, q = DQ[i]
        cumsat = change_schedule(D, C, S, T, d, q, cumsat)
        T[d] = q
        print(cumsat)


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Submission status: Accepted

Solution code:
from bisect import bisect_left,insort_left

#入力
D = int(input())
C = [int(c) for c in input().split()]
S = []
for _ in range(D):
    s = [int(x) for x in input().split()]
    S.append(s)
T = []
for _ in range(D):
    t = int(input()) - 1
    T.append(t)
    
#スコア計算
score = 0
last_day = [[-1] for _ in range(26)]
for d in range(D):
    test = T[d]
    score += S[d][test]
    last_day[test].append(d)
minus = [0] * 26
for i in range(26):
    last_day[i].append(D)
    l = last_day[i]
    for j in range(len(l)-1):
        dd = l[j+1] - l[j] - 1
        minus[i] += C[i] * (dd * (dd + 1)) // 2
    score -= minus[i]

M = int(input())
for _ in range(M):
    d,q = map(int,input().split())
    d -= 1
    q -= 1
    old = T[d]
    T[d] = q
    #日程dでの元のテストold
    l = last_day[old]
    ind_old = l.index(d)
    dd_left = l[ind_old] - l[ind_old-1] - 1
    dd_right = l[ind_old+1] - l[ind_old] - 1
    dd = l[ind_old+1] - l[ind_old-1] - 1
    dif_old = C[old] * (((dd_left * (dd_left + 1)) // 2) + ((dd_right * (dd_right + 1)) // 2) - ((dd * (dd + 1)) // 2))
    #日程dでのテストq
    l = last_day[q]
    ind_q = bisect_left(last_day[q],d)
    dd_left = d - l[ind_q-1] - 1
    dd_right = l[ind_q] - d - 1
    dd = l[ind_q] - l[ind_q-1] - 1
    dif_q = C[q] * (((dd * (dd + 1)) // 2) - ((dd_left * (dd_left + 1)) // 2) - ((dd_right * (dd_right + 1)) // 2))
    #新しいスコア
    score += (dif_old + dif_q - S[d][old] + S[d][q])
    #情報の更新
    minus[old] -= dif_old
    minus[q] -= dif_q
    del last_day[old][ind_old]
    last_day[q].insert(ind_q,d)
    print(score)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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


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


def update_score(D, C, S, T, score, ct, ci):
    """
    ct日目のコンテストをコンテストciに変更する
    スコアを差分更新する

    ct: change t 変更日 0-indexed
    ci: change i 変更コンテスト 0-indexed
    """
    new_score = score
    last = [0]*26  # コンテストiを前回開催した日
    prei = T[ct]  # 変更前に開催する予定だったコンテストi
    for d, t in enumerate(T, start=1):
        last[t] = d
        new_score += (d - last[prei])*C[prei]
        new_score += (d - last[ci])*C[ci]
    last = [0]*26
    for d, t in enumerate(T, start=1):
        if d-1 == ct:
            last[ci] = d
        else:
            last[t] = d
        new_score -= (d - last[prei])*C[prei]
        new_score -= (d - last[ci])*C[ci]
    new_score -= S[ct][prei]
    new_score += S[ct][ci]
    return new_score


def local_search():
    pass


def main(D, C, S):
    T = []
    for d in range(D):
        # d日目終了時点で満足度が一番高くなるようなコンテストiを開催する
        max_score = -INF
        best_i = 1
        for i in range(26):
            T.append(i)
            score = calc_score(D, C, S, T)
            if max_score < score:
                max_score = score
                best_i = i
            T.pop()
        T.append(best_i)
    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())-1 for i in range(D)]
    M = int(input())
    DQ = [[int(i)-1 for i in input().split()] for j in range(M)]
    score = calc_score(D, C, S, T)
    for d, q in DQ:
        score = update_score(D, C, S, T, score, d, q)
        T[d] = q
        print(score)

Submission status: Accepted

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


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


def update_score(D, C, S, T, score, ct, ci):
    """
    ct日目のコンテストをコンテストciに変更する
    スコアを差分更新する

    ct: change t 変更日 0-indexed
    ci: change i 変更コンテスト 0-indexed
    """
    new_score = score
    last = [0]*26  # コンテストiを前回開催した日
    prei = T[ct]  # 変更前に開催する予定だったコンテストi
    for d, t in enumerate(T, start=1):
        last[t] = d
        new_score += (d - last[prei])*C[prei]
        new_score += (d - last[ci])*C[ci]
    last = [0]*26
    T[ct] = ci
    for d, t in enumerate(T, start=1):
        last[t] = d
        new_score -= (d - last[prei])*C[prei]
        new_score -= (d - last[ci])*C[ci]
    new_score -= S[ct][prei]
    new_score += S[ct][ci]
    return new_score


def local_search():
    pass


def main(D, C, S):
    T = []
    for d in range(D):
        # d日目終了時点で満足度が一番高くなるようなコンテストiを開催する
        max_score = -INF
        best_i = 1
        for i in range(26):
            T.append(i)
            score = calc_score(D, C, S, T)
            if max_score < score:
                max_score = score
                best_i = i
            T.pop()
        T.append(best_i)
    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())-1 for i in range(D)]
    M = int(input())
    DQ = [[int(i)-1 for i in input().split()] for j in range(M)]
    score = calc_score(D, C, S, T)
    for d, q in DQ:
        score = update_score(D, C, S, T, score, d, q)
        T[d] = q
        print(score)

Submission status: Accepted

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


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


def update_score(D, C, S, T, score, ct, ci):
    """
    ct日目のコンテストをコンテストciに変更する
    スコアを差分更新する

    ct: change t 変更日 0-indexed
    ci: change i 変更コンテスト 0-indexed
    """
    last = [0]*26  # コンテストiを前回開催した日
    for d in range(ct):
        last[T[d]] = d + 1
    prei = T[ct]  # 変更前に開催する予定だったコンテストi
    score -= S[ct][prei]
    score += S[ct][ci]
    for d in range(ct, D):
        if d != ct and T[d] == prei:
            break
        score += C[prei]*(d + 1 - ct - 1)
        score -= C[prei]*(d + 1 - last[prei])
    for d in range(ct, D):
        if d != ct and T[d] == ci:
            break
        score += C[ci]*(d + 1 - last[ci])
        score -= C[ci]*(d + 1 - ct - 1)
    T[ct] = ci
    return score, T


def local_search():
    pass


def main(D, C, S):
    T = []
    for d in range(D):
        # d日目終了時点で満足度が一番高くなるようなコンテストiを開催する
        max_score = -INF
        best_i = 1
        for i in range(26):
            T.append(i)
            score = calc_score(D, C, S, T)
            if max_score < score:
                max_score = score
                best_i = i
            T.pop()
        T.append(best_i)
    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())-1 for i in range(D)]
    M = int(input())
    DQ = [[int(i)-1 for i in input().split()] for j in range(M)]
    score = calc_score(D, C, S, T)
    for d, q in DQ:
        score, T = update_score(D, C, S, T, score, d, q)
        print(score)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
D = int(input())
C = list(map(int,input().split()))
S = [list(map(int,input().split())) for i in range(D)]
T = [int(input()) for i in range(D)]
M = int(input())
DQ = [tuple(map(int,input().split())) for i in range(M)]

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

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

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

Submission status: Accepted

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

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

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

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

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

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

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

        print(ans)

if __name__=="__main__":
    main()

Submission status: Accepted

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

def scoring(sc):
    last = [0] * 26
    res = 0
    penalty = 0
    for i in range(D):
        t = out[i]
        res += S[i][t]
        penalty += sc - (i + 1 - last[t]) * C[t]
        res -= penalty
        last[t] = i + 1
    return res

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

Submission status: Accepted

Solution code:
from numba import njit
from numpy import int64,zeros
@njit('i8(i8[:],i8[:])',cache=True)
def func(s,x):
    last=zeros(26,int64)
    score=0
    for i,v in enumerate(x,1):
        last[v]=i
        c=0
        for j in range(26):
            c+=s[j]*(i-last[j])
        score+=s[i*26+v]-c
    return score
def main():
    d,*s=map(int,open(0).read().split())
    s=int64(s)
    x=s[26*-~d:d*27+26]-1
    for d,q in s[27*-~d:].reshape(-1,2):
        x[d-1]=q-1
        print(func(s,x))
main()

Submission status: Accepted

Solution code:
from numba import njit
from numpy import int64
@njit('i8(i8[:],i8[:])',cache=True)
def func(s,x):
    last=[0]*26
    score=0
    for i,v in enumerate(x,1):
        last[v]=i
        c=0
        for j in range(26):
            c+=s[j]*(i-last[j])
        score=score+s[i*26+v]-c
    return score
def main():
    d,*s=map(int,open(0).read().split())
    s=int64(s)
    x=s[26*-~d:d*27+26]-1
    for d,q in s[27*-~d:].reshape(-1,2):
        x[d-1]=q-1
        print(func(s,x))
main()

Submission status: Accepted

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

def f(X):
    score = 0
    L = [-1 for j in range(26)]
    A = [0 for j in range(26)]
    for i in range(d):
        score += S[i][X[i]]
        A[X[i]] += (i - L[X[i]]) * (i - L[X[i]] - 1) // 2
        L[X[i]] = i
    for j in range(26):
        A[j] += (d - L[j]) * (d - L[j] - 1) // 2
        score -= C[j] * A[j]
    return score

X = [int(input()) - 1 for i in range(d)]
m = int(input())
for k in range(m):
    i, j = map(lambda x: int(x) - 1, input().split())
    X[i] = j
    print(f(X))

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left

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

def get_sum(a, d, n):
    """ 等差数列の和：(初項a, 公差d, 項数n) """
    return (2*a + (n-1)*d) * n // 2

D = INT()
M = 26
C = LIST()
S = [[]] * (D+1)
S[0] = [0] * M
for i in range(1, D+1):
    S[i]  = LIST()
adjli = [[0] for i in range(M)]
T = [0] + [t-1 for t in LIST(D)]
for d, t in enumerate(T[1:], 1):
    adjli[t].append(d)
for i in range(M):
    adjli[i].append(D+1)

def check(T):
    score = 0
    for a in range(M):
        for i in range(1, len(adjli[a])):
            curd = adjli[a][i-1]
            nxtd = adjli[a][i]
            cnt = nxtd - curd
            score += S[curd][a]
            score -= C[a] * get_sum(0, 1, cnt)
    return score

# day日目のコンテストをaからbに変更する
def change(day, a, b):
    res = 0
    # コンテストaのコストを再計算
    res -= S[day][a]
    di = adjli[a].index(day)
    for i in range(di, di+2):
        curd = adjli[a][i-1]
        nxtd = adjli[a][i]
        cnt = nxtd - curd
        res += C[a] * get_sum(0, 1, cnt)
    adjli[a].pop(di)
    curd = adjli[a][di-1]
    nxtd = adjli[a][di]
    cnt = nxtd - curd
    res -= C[a] * get_sum(0, 1, cnt)

    # コンテストbのコストを再計算
    res += S[day][b]
    di = bisect_left(adjli[b], day)
    curd = adjli[b][di-1]
    nxtd = adjli[b][di]
    cnt = nxtd - curd
    res += C[b] * get_sum(0, 1, cnt)
    adjli[b].insert(di, day)
    for i in range(di, di+2):
        curd = adjli[b][i-1]
        nxtd = adjli[b][i]
        cnt = nxtd - curd
        res -= C[b] * get_sum(0, 1, cnt)

    return res

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

    score += change(d, T[d], q)
    print(score)
    T[d] = q

Submission status: Accepted

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+1)
for i in range(1, D+1):
    S[i]  = LIST()
T = [0] + [t-1 for t in LIST(D)]
M = 26

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

def change(day, a, b):
    nxtday = last[a].index(0, day+1)
    w = nxtday - day
    h = last[a][day-1] + 1
    a_change = C[a] * h * w
    for d in range(day, nxtday):
        last[a][d] = last[a][d-1] + 1

    nxtday = last[b].index(0, day+1)
    w = nxtday - day
    h = last[b][day-1] + 1
    b_change = C[b] * h * w
    last[b][day] = 0
    for d in range(day+1, nxtday):
        last[b][d] = last[b][d-1] + 1

    res = -a_change + b_change - S[day][a] + S[day][b]
    return res

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

    prev = T[d]
    nxt = q
    score += change(d, prev, nxt)
    print(score)
    T[d] = q