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: Wrong Answer

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, dp3, dq1, dq3 = -1, D, -1, 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):
        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: Wrong Answer

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 evaluate(D, C, S, T, k):
    """
    d日目終了時点での満足度を計算し，
    d + k日目終了時点での満足度の減少も考慮する
    """
    score = 0
    last = [0]*26
    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]

    for d in range(len(T), min(len(T) + k, D)):
        for i in range(26):
            score -= (d + 1 - last[i]) * C[i]
    return score


def greedy(D, C, S):
    Ts = []
    for k in range(5, 13):
        T = []  # 0-indexed
        max_score = -INF
        for d in range(D):
            # d+k日目終了時点で満足度が一番高くなるようなコンテストiを開催する
            max_score = -INF
            best_i = 0
            for i in range(26):
                T.append(i)
                score = evaluate(D, C, S, T, k)
                if max_score < score:
                    max_score = score
                    best_i = i
                T.pop()
            T.append(best_i)
        Ts.append((max_score, T))
    return max(Ts, key=lambda pair: pair[0])


def local_search(D, C, S, score, T):
    # ct 日目のコンテストをciに変更
    for k in range(50000):
        ct = randint(0, D-1)
        ci = randint(0, 25)
        ori = T[ct]
        new_score = update_score(D, C, S, T, score, ct, ci)
        T[ct] = ci
        if score < new_score:
            score = new_score
        else:
            T[ct] = ori
    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)]
    init_score, T = greedy(D, C, S)
    T = local_search(D, C, S, init_score, T)
    for t in T:
        print(t+1)

Submission status: Wrong Answer

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 evaluate(D, C, S, T, k):
    """
    d日目終了時点での満足度を計算し，
    d + k日目終了時点での満足度の減少も考慮する
    """
    score = 0
    last = [0]*26
    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]

    for d in range(len(T), min(len(T) + k, D)):
        for i in range(26):
            score -= (d + 1 - last[i]) * C[i]
    return score


def greedy(D, C, S):
    Ts = []
    for k in range(5, 13):
        T = []  # 0-indexed
        max_score = -INF
        for d in range(D):
            # d+k日目終了時点で満足度が一番高くなるようなコンテストiを開催する
            max_score = -INF
            best_i = 0
            for i in range(26):
                T.append(i)
                score = evaluate(D, C, S, T, k)
                if max_score < score:
                    max_score = score
                    best_i = i
                T.pop()
            T.append(best_i)
        Ts.append((max_score, T))
    return max(Ts, key=lambda pair: pair[0])


def local_search(D, C, S, score, T):
    for _ in range(800):
        ct = randint(0, D-1)
        ci = randint(0, 25)
        ori = T[ct]
        T[ct] = ci
        new_score = calc_score(D, C, S, T)
        # 差分更新がバグってそう
        if score < new_score:
            score = new_score
        else:
            T[ct] = ori

    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)]
    init_score, T = greedy(D, C, S)
    T = local_search(D, C, S, init_score, T)
    for t in T:
        print(t+1)

Submission status: Wrong Answer

Solution code:
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])

print(ans)

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)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

s_grid = []
for i in range(D):
    array = list(map(int, input().strip().split(' ')))
    s_grid.append(array)

t_list = [int(input()) -1 for i in range(D)] #task_list

M = int(input())
d_grid = []
for i in range(M):
    array = list(map(int, input().strip().split(' ')))
    d_grid.append(array)

def calculate_score(t_list,score_list,last_grid,change_query_number):
    score_list = score_list[:change_query_number]
    last_grid = last_grid[:change_query_number]

    if len(score_list) > 1:
        score = score_list[-1]
        last_list = last_grid[-1]
    else:
        score = 0
        last_list = [0 for i in range(26)]

    for d in range(change_query_number,D):
        score += s_grid[d][t_list[d]]
        last_list = [n+1 for n in last_list]
        last_list[t_list[d]] = 0
        for i in range(26):
            score -= c_list[i]*last_list[i]
        score_list.append(score)
        last_grid.append(last_list)
    return score_list , last_grid

#first cal.
previous_s, previous_l = calculate_score(t_list,[],[[0 for i in range(26)]],0)

for i in range(M):
    j = d_grid[i][0] - 1
    t_list[j] = d_grid[i][1] -1
    score_list , last_grid = calculate_score(t_list,previous_s,previous_l,j)
    print(score_list[-1])
    previous_s = score_list
    previous_l = last_grid

Submission status: Wrong Answer

Solution code:
class Heruistics:
    donelist = [0]*26
    result = 0
    contestlist = []
    def __init__(self,days):
        self.days = days
        self.clast = list(map(int,input().split()))
        self.allpref = [] #allpref[day][contest]
        for i in range(days):
            self.allpref.append(list(map(int,input().split())))

    def scoring(self):
        self.result = 0
        self.donelist = [0]*26
        for i in range(self.days):
            cont = self.contestlist[i]
            self.donelist[cont-1] = i+1
            zanen = sum([self.clast[j]*((i+1)-self.donelist[j]) for j in range(26)])
            self.result += self.allpref[i][cont-1] - zanen


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

            self.donelist[contest] = i+1
            self.contestlist.append(contest+1)

    def kyokusho(self,day,cont):
        self.contestlist[day-1] = cont


greed_heru = Heruistics(int(input()))
for i in range(greed_heru.days):
    greed_heru.contestlist.append(int(input()))

M = int(input())
dq = []
for i in range(M):
    d,q = map(int,input().split())
    dq.append([d,q])

for i in range(M):
    greed_heru.kyokusho(dq[i][0],dq[i][1])
    print(greed_heru.result)

Submission status: Wrong Answer

Solution code:
class Heruistics:
    donelist = [0]*26
    resultlist = []
    contestlist = []
    def __init__(self,days):
        self.days = days
        self.clast = list(map(int,input().split()))
        self.allpref = [] #allpref[day][contest]
        for i in range(days):
            self.allpref.append(list(map(int,input().split())))

    def scoring(self):
        result = 0
        tempdonelist = self.donelist[:]
        for i in range(self.days):
            cont = self.contestlist[i]
            tempdonelist[cont-1] = i+1
            zanen = sum([self.clast[j]*((i+1)-tempdonelist[j]) for j in range(26)])

            result += self.allpref[i][cont-1] - zanen
        return result

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

            self.donelist[contest] = i+1
            self.contestlist.append(contest+1)

    def kyokusho(self,day,cont):
        self.contestlist[day-1] = cont


greed_heru = Heruistics(int(input()))
for i in range(greed_heru.days):
    greed_heru.contestlist.append(int(input()))
print(greed_heru.scoring())

M = int(input())
dq = []
for i in range(M):
    d,q = map(int,input().split())
    dq.append([d,q])

for i in range(M):
    greed_heru.kyokusho(dq[i][0],dq[i][1])
    print(greed_heru.scoring())

Submission status: Wrong Answer

Solution code:
class Heruistics:
    donelist = [0]*26
    resultlist = []
    contestlist = []
    def __init__(self,days):
        self.days = days
        self.clast = list(map(int,input().split()))
        self.allpref = [] #allpref[day][contest]
        for i in range(days):
            self.allpref.append(list(map(int,input().split())))

    def scoring(self):
        result = 0
        for i in range(self.days):
            cont = self.contestlist[i]
            self.donelist[cont-1] = i+1
            zanen = sum([self.clast[j]*((i+1)-self.donelist[j]) for j in range(26)])

            result += self.allpref[i][cont-1] - zanen
        return result

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

            self.donelist[contest] = i+1
            self.contestlist.append(contest+1)

    def kyokusho(self,day,cont):
        old = self.contestlist[day-1]
        self.contestlist[day-1] = cont


greed_heru = Heruistics(int(input()))
for i in range(greed_heru.days):
    greed_heru.contestlist.append(int(input()))

M = int(input())
dq = []
for i in range(M):
    d,q = map(int,input().split())
    dq.append([d,q])

for i in range(M):
    greed_heru.kyokusho(dq[i][0],dq[i][1])
    print(greed_heru.scoring())

Submission status: Wrong Answer

Solution code:
import bisect
import random
import sys

input = sys.stdin.readline


class scores:
    def __init__(self, t):
        self.t = t

    def first_score(self):
        ans = 0
        for i in range(D):
            ti = self.t[i]
            ans += S[i][ti - 1]
            for j in range(1, 27):
                ans -= C[j - 1] * (i + 1 - self.last(i + 1, j))
        self.current_score = ans

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

    def update(self, d, q):
        # print(self.current_score)
        d -= 1
        q -= 1
        old_q = self.t[d]
        self.current_score -= S[d][old_q - 1]
        self.current_score += S[d][q]
        for i in range(d + 1, D + 1):  # 新しいやつの不満度
            self.current_score -= C[q] * (i * d + 1)

        self.t[d] = q + 1
        #old_hol = [i + 1 for i in range(D) if self.t[i] == old_q]
        #for i in range()
        return self.current_score


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)
sc = scores(T)
sc.first_score()


v = []
for i in range(int(input())):
    a, b = map(int, input().split())
    print(sc.update(a, b))

Submission status: Wrong Answer

Solution code:
import bisect
import random
import sys

input = sys.stdin.readline


class scores:
    def __init__(self, t):
        self.t = t

    def first_score(self):
        ans = 0
        for i in range(D):
            ti = self.t[i]
            ans += S[i][ti - 1]
            for j in range(1, 27):
                ans -= C[j - 1] * (i + 1 - self.last(i + 1, j))
        self.current_score = ans

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

    def update(self, d, q):
        # print(self.current_score)
        d -= 1
        q -= 1
        old_q = self.t[d]
        self.current_score -= S[d][old_q - 1]
        self.current_score += S[d][q]
        for i in range(d + 1, D + 1):  # 新しいやつの不満度
            self.current_score -= C[q] * (i * d + 1)

        self.t[d] = q + 1
        old_hol = [i + 1 for i in range(D) if self.t[i] == old_q]
        #for i in range()
        return self.current_score


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)
sc = scores(T)
sc.first_score()


v = []
for i in range(int(input())):
    a, b = map(int, input().split())
    print(sc.update(a, b))

Submission status: Wrong Answer

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
    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())
    old=t[day-1]
    t[day-1]=q
    ans=calc(t)
    print(ans)
    t[day-1]=old

Submission status: Wrong Answer

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

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

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

    nxtday = last[b].index(0, day+2)
    w = nxtday - (day+1)
    h = last[b][day] + 1
    b_change = C[b] * h * w
    for d in range(day, nxtday-1):
        last[b][d+1] = last[b][d] + 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()
    d -= 1; q -= 1

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

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left

D = int(input())
C = [0]+list(map(int, input().split()))

S = [0]+[[0] + list(map(int, input().split())) for _ in range(D)]

contest = [[0] for _ in range(27)]

#SL:満足度、sch：スケジュール
SL, sch = 0, [0]

#tの日程でコンテストを行った時の満足度を計算
for d in range(1, D+1):
    t = int(input())
    sch.append(t)
    #コンテストの開催日時を記録
    contest[t].append(d)
    SL += S[d][t]

    for i in range(1, 27):
        SL -= C[i]*(d-contest[i][-1])

for i in range(1, 27):
    contest[i].append(D+1)

# print("contest", contest)
# print("sch", sch)
# print(S)
M = int(input())
for i in range(M):
    d, q = map(int, input().split())
    SL += S[d][q]-S[d][sch[d]]

    # print("1", contest[sch[d]])
    ind = bisect_left(contest[sch[d]], d)
    # print("2", ind)
    k = d-contest[sch[d]][ind-1]
    l = contest[sch[d]][ind+1]-d
    SL -= C[sch[d]]*k*l
    del contest[sch[d]][ind]

    ind = bisect_left(contest[q], d)
    contest[q].insert(ind, d)
    k = d-contest[q][ind-1]
    l = contest[q][ind+1]-d
    SL += C[q]*k*l
    sch[d] = q
    # print(SL)