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:
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 = [[-1] for i in range(26)]
# before query
ans = 0
for i in range(D):
    op = t[i]-1
    ans += s[i][op]
    last[op].append(i)
    for j in range(26):
        ans -= c[j]*(i-last[j][-1])
    # print(ans)
from bisect import *
import random
m = int(input())
def suminc(a,b):
    return b*(b-1)//2-a*(a-1)//2
while m:
    m-=1
    update = 0
    d,q = map(int, input().split())
    # d = random.randint(1,365)
    # q = random.randint(1,26)
    d-=1
    q-=1
    oq = t[d]-1
    update += s[d][q]-s[d][oq]
    idx = bisect_left(last[oq],d)
    if idx == len(last[oq])-1:
        cnt = D - last[oq][idx]
    else:
        cnt = last[oq][idx+1] - last[oq][idx]
    update += c[oq]*suminc(0,cnt)
    cntprv = last[oq][idx] - last[oq][idx-1]
    update -= c[oq]*suminc(cntprv,cntprv+cnt)

    idx2 = bisect_left(last[q],d)-1
    if idx2 == len(last[q])-1:
        cnt = D - d
    else:
        cnt = last[q][idx2+1] - d
    if idx2 == len(last[q])-1:
        cntprv = D - last[q][idx2] - cnt
    else:
        cntprv = last[q][idx2+1] - last[q][idx2] - cnt
    update += c[q]*suminc(cntprv,cntprv+cnt)
    update -= c[q]*suminc(0,cnt)

    ans += update
    del last[oq][idx]
    last[q].insert(idx2+1,d)
    print(ans)
    t[d] = q+1

Submission status: Accepted

Solution code:
import sys, heapq

def calcScore_change(D, complaints, satisfications, HoldedContestDays, N_queues, queues):
    TotalSatisfication = 0
    ContestDays_List = [ [i+1] * 26 for i in range(D) ] # [D][j]

    complaint_all = 0
    for i in range(26):
        complaint_all += complaints[i]

    complaint_sum = 0
    for i in range(D):
        complaint_sum += complaint_all
        Contest = HoldedContestDays[i]
        complaint_sum -= ContestDays_List[i][Contest] * complaints[Contest]
        ContestDays_List[i][Contest] = 0

        TotalSatisfication += satisfications[i][Contest] - complaint_sum

        for j in range(i+1, D):
            ContestDays_List[j][Contest] = ContestDays_List[j-1][Contest] + 1

    scores_afterchanging = [TotalSatisfication]
    for m in range(N_queues):
        queue = queues[m]

        day = queue[0]
        contest_change = queue[1]
        contest_old = HoldedContestDays[day]

        # 1. 元のコンテスト変化
        nextcontest = D
        for i in range(day+1, D):
            if(HoldedContestDays[i]==contest_old):
                nextcontest = i
                break
        for i in range(day, nextcontest):
            if(i==0):
                ContestDays_List[i][contest_old] = 1
            else:
                ContestDays_List[i][contest_old] = ContestDays_List[i-1][contest_old]+1
        if(day==0):
            changed_s = 1
        else:
            changed_s = ContestDays_List[day-1][contest_old]+1

        score_change = -changed_s * (nextcontest-day) * complaints[contest_old]

        # 2. その代わりに開催
        nextcontest_new = D
        for i in range(day+1, D):
            if(HoldedContestDays[i]==contest_change):
                nextcontest_new = i
                break
        k = 0
        for i in range(day, nextcontest_new):
            ContestDays_List[i][contest_change] = k
            k+= 1
        if(day==0):
            changed_s2 = 1
        else:
            changed_s2 = ContestDays_List[day-1][contest_change]+1
        change = changed_s2 * (nextcontest_new-day) * complaints[contest_change]
        score_change += change

        #3. score
        score_change += satisfications[day][contest_change] - satisfications[day][contest_old]

        score = scores_afterchanging[-1] + score_change
        scores_afterchanging.append(score)
        HoldedContestDays[day] = contest_change
    return scores_afterchanging
    """
    TotalSatisfication: 変更前のスコア
    di Contest ->qiに変更すると:
        もとのHoldedContestDays, ContestDays_Listの変更を忘れないように

        元のコンテストContestからqiへ変更
        1) ContestDays_List[d][Contest] = ContestDays_List[d-1][Contest] +1になる(次にコンテストが行われ0に初期化される日をd_nextとするとd_next-1まで)
        結果、満足度は (ContestDays_List[di-1][Contest]+1) * (d_next-di) * complaints[Contest]現象

        2)その代わり実行されたコンテストは(qiの次の実行びをd_next_2として)
        (ContestDays_List[di-1][qi]+1) * (d_next_2-di) * complaints[qi]増加

        3)さらに、s[di][qi]-s[di][Contest]上昇
          5 0 1 2 3 0
        ->5 6 7 8 9 0
    """










"""
13: 19922, 89
20: 19830, 80

20: 19830 - 80 * 5 = 19430
13: 19922 - 89 * 2 = 19744
毎日1つのコンテスト
満足度をあげるようにコンテスト
ci * (最後にコンテストを行ってからの経過日数)満足度低下
上昇値はs_d_i

"""
if(__name__ == "__main__"):
    D = int(input().strip())
    complaints = list(map(int, input().split() ) )

    satisfications = []
    for i in range(D):
        satisfication = list(map(int, input().split() ) )
        satisfications.append(satisfication)
    HoldedContestDays =[0] * D
    for i in range(D):
        HoldedContestDays[i] = int(input().strip())
        HoldedContestDays[i] -= 1
    N_queues = int(input().strip())
    queues = []
    for m in range(N_queues):
        queue = list(map(int, input().split() ) )
        queue[0] -= 1
        queue[1] -= 1
        queues.append(queue)
    Score_change = calcScore_change(D, complaints, satisfications, HoldedContestDays, N_queues, queues)

    for m in range(N_queues):
        print(Score_change[m+1])

Submission status: Accepted

Solution code:
D = int(input())
C = [int(x) for x in input().split()]
S = [[int(i) for i in input().split()] for D in range(D)]
T = [0]*D
for i in range(D):
    T[i] = int(input())
M = int(input())
dp = [[int(i) for i in input().split()] for M in range(M)]

score = [0]*26
last = [-1]*26

for i in range(D):
    score[T[i]-1] += S[i][T[i]-1]
    last[T[i]-1] = i

    for j in range(26):
        score[j] -= C[j]*(i-last[j])

for k in range(M):
    x = T[dp[k][0]-1]
    y = dp[k][1]
    T[dp[k][0]-1] = y
    score[x-1] = 0
    score[y-1] = 0
    last[x-1] = -1
    last[y-1] = -1
    for i in range(D):
        if T[i] == x or T[i] == y:
            score[T[i]-1] += S[i][T[i]-1]
            last[T[i]-1] = i

        score[x-1] -= C[x-1]*(i-last[x-1])
        score[y-1] -= C[y-1]*(i-last[y-1])

    print(sum(score))

Submission status: Accepted

Solution code:
import numpy as np
from bisect import bisect_left

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

L = np.empty(26, int)
L[:] = -1

X = [[-1] for _ in range(26)]
T = []

score = 0
for d in range(D):
    t = int(input())-1
    T.append(t)
    L[t] = d
    score += S[d, t] - np.dot(C, d-L)
    X[t].append(d)

for x in X:
    x.append(D)
    
M = int(input())
for _ in range(M):
    d, q = map(int, input().split())
    d-=1
    q-=1

    t = T[d]
    T[d] = q
    
    i = bisect_left(X[t], d)
    d_prev = X[t][i-1]
    d_next = X[t][i+1]
    
    dd = d-d_prev-1
    score += C[t]*(dd+1)*dd//2
    dd = d_next-d-1
    score += C[t]*(dd+1)*dd//2
    dd = d_next-d_prev-1
    score -= C[t]*(dd+1)*dd//2

    X[t].pop(i)
    
    i = bisect_left(X[q], d)
    d_prev = X[q][i-1]
    d_next = X[q][i]
    
    dd = d-d_prev-1
    score -= C[q]*(dd+1)*dd//2
    dd = d_next-d-1
    score -= C[q]*(dd+1)*dd//2
    dd = d_next-d_prev-1
    score += C[q]*(dd+1)*dd//2

    X[q].insert(i, d)

    score += S[d,q] - S[d,t]

    print(score)

Submission status: Accepted

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

def scoring(d, c, s, t):
    v = []
    memo = [0 for _ in range(26)]
    for i in range(d):
        if i == 0:
            score = 0
        else:
            score = v[-1]
        score += s[i][t[i]]
        memo[t[i]] = i + 1
        for j in range(26):
            score -= c[j] * (i+1 - memo[j])

        v.append(score)

    return v[-1]

score = scoring(d, c, s, t)

m = int(input())
memo = [[0 for _ in range(26)]]
for i in range(d):
    l = memo[-1]
    l[t[i]] = i+1
    memo.append(l)

for _ in range(m):
    x, y = map(int, input().split())
    x -= 1
    y -= 1
    before_ti, after_ti = 0, d+1
    before_y, after_y = 0, d+1

    for i in range(x):
        if t[i] == t[x]:
            before_ti = i+1
        if t[i] == y:
            before_y = i+1

    for i in range(x+1, d):
        if t[i] == t[x]:
            after_ti = i+1
            break
    for i in range(x+1, d):
        if t[i] == y:
            after_y = i+1
            break

    score -= s[x][t[x]]
    score += s[x][y]
    score -= c[t[x]] * (x + 1 - before_ti) * (after_ti - x - 1)
    score += c[y] * (x + 1 - before_y) * (after_y - x - 1)

    t[x] = y

    print(score)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))


D = ini()
C = inl()
assert len(C) == 26
S = [None] * D
for i in range(D):
    S[i] = inl()
    assert len(S[i]) == 26
T = [ini() - 1 for _ in range(D)]
changes = []
M = ini()
for i in range(M):
    d, q = inm()
    d -= 1
    q -= 1
    changes.append((d, q))
# changes.sort()


def main():
    last = [[-1] * (D + 1) for _ in range(26)]
    score = 0
    for d in range(D):
        ct = T[d]
        score += S[d][ct]
        for i in range(26):
            last[i][d + 1] = last[i][d]
        last[ct][d + 1] = d
        for i in range(26):
            score -= C[i] * (d - last[i][d + 1])

    for d, after in changes:
        before = T[d]
        if before == after:
            continue
        score -= S[d][before]
        score += S[d][after]
        lb = last[before][d]
        la = last[after][d]
        da = db = 0
        for x in range(d, D):
            if x > d and T[x] == before:
                break
            last[before][x + 1] = lb
            db += 1
        score -= C[before] * (d - lb) * db
        for x in range(d, D):
            if T[x] == after:
                break
            last[after][x + 1] = d
            da += 1
        score += C[after] * (d - la) * da
        T[d] = after
        print(score)


main()

Submission status: Accepted

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
def main(D, C, S, T, M, Q):
    def evaluate(i, t, satisfaction, last):
        satisfaction += S[i][t]
        last[t] = i
        for j, c in enumerate(C):
            satisfaction -= c * (i - last[j])
        return (satisfaction, last)

    satisfaction = 0
    last = [-1] * 26
    count = [BinaryIndexedTree(D) for _ in range(26)]
    for i, t in enumerate(T):
        satisfaction, last = evaluate(i, t, satisfaction, last)
        count[t].add(i, 1)

    for d, new in Q:
        old = T[d]
        satisfaction += S[d][new] - S[d][old]
        cnt_old = count[old].query(d)
        nxt_d_old = count[old].bisect(lambda x: x < cnt_old + 1)
        pre_d_old = count[old].bisect(lambda x: x < cnt_old - 1) if cnt_old > 1 else -1
        satisfaction -= C[old] * (nxt_d_old - d) * (d - pre_d_old)
        T[d] = new
        count[old].add(d, -1)
        count[new].add(d, 1)
        cnt_new = count[new].query(d)
        nxt_d_new = count[new].bisect(lambda x: x < cnt_new + 1)
        pre_d_new = count[new].bisect(lambda x: x < cnt_new - 1) if cnt_new > 1 else -1
        satisfaction += C[new] * (nxt_d_new - d) * (d - pre_d_new)
        print(satisfaction)

class BinaryIndexedTree:
    def __init__(self, n=None, f=lambda x, y: x + y, identity=0, initial_values=None):
        assert(n or initial_values)
        self.__f, self.__id, = f, identity
        self.__n = len(initial_values) if initial_values else n
        self.__d = [identity] * (self.__n + 1)
        if initial_values:
            for i, v in enumerate(initial_values): self.add(i, v)

    def add(self, i, v):
        n, f, d = self.__n, self.__f, self.__d
        i += 1
        while i <= n:
            d[i] = f(d[i], v)
            i += -i & i

    def query(self, r):
        res, f, d = self.__id, self.__f, self.__d
        r += 1
        while r:
            res = f(res, d[r])
            r -= -r & r
        return res

    def bisect(self, func):
        n, f, d, v = self.__n, self.__f, self.__d, self.__id
        x, i = 0, 1 << (n.bit_length() - 1)
        while i > 0:
            if x + i <= n and func(f(v, d[x + i])): v, x = f(v, d[x + i]), x + i
            i >>= 1
        return x

if __name__ == '__main__':
    input = sys.stdin.readline
    D = int(input())
    *C, = map(int, input().split())
    S = [list(map(int, input().split())) for _ in range(D)]
    T = [int(input()) - 1 for _ in range(D)]
    M = int(input())
    Q = [tuple(map(lambda x:int(x) - 1, input().split())) for _ in range(M)]
    main(D, C, S, T, M, Q)

Submission status: Accepted

Solution code:
from time import time
from random import randrange
from bisect import bisect_left
import sys
def input():
	return sys.stdin.buffer.readline()[:-1]
start = time()
d = int(input())
c = list(map(int, input().split()))
C = sum(c)
s = [list(map(int, input().split())) for _ in range(d)]
#t = [int(input()) for _ in range(d)]
t = []
day = [[0] for _ in range(26)]
order = []

def score(t):
	res = 0
	minus = 0
	last = [0 for _ in range(26)]
	for i, x in enumerate(t):
		minus += C - c[x-1] * (i - last[x-1] + 1)
		res -= minus
		res += s[i][x-1]
		last[x-1] = i+1
		#print(res)
	return res

def tri(n):
	return n * (n-1) // 2

def change(i, to):
	diff = 0
	fr = t[i]-1
	#print(day[fr])
	#print(day[to])
	if fr == to:
		return 0
	fr_ind = bisect_left(day[fr], i+1)
	diff += (tri(day[fr][fr_ind] - day[fr][fr_ind-1]) + tri(day[fr][fr_ind+1] - day[fr][fr_ind])) * c[fr]
	diff -= (tri(day[fr][fr_ind+1] - day[fr][fr_ind-1])) * c[fr]
	diff -= s[i][fr]
	
	to_ind = bisect_left(day[to], i+1)
	diff += (tri(day[to][to_ind] - day[to][to_ind-1])) * c[to]
	diff -= (tri(day[to][to_ind] - (i+1)) + tri(i+1 - day[to][to_ind-1])) * c[to]
	diff += s[i][to]

	#if diff > 0:
	day[fr].pop(fr_ind)
	after = day[to][:to_ind] + [i+1] + day[to][to_ind:]
	day[to] = after
	t[i] = to+1
	#print("↓")
	#print(day[fr])
	#print(day[to])
	return diff
	#else:
		#return False

#score(t)
res = 0
minus = 0
last = [0 for _ in range(26)]
for i in range(d):
	minus += C
	#li = sorted(list(range(26)), key=lambda x: - c[x] * (i - last[x] + 1) - s[i][x])
	#order.append(li)
	#M_ind = li[0]
	M_ind = int(input())-1
	minus -= c[M_ind] * (i - last[M_ind] + 1)
	last[M_ind] = i+1
	res -= minus - s[i][M_ind]
	t.append(M_ind+1)
	day[M_ind].append(i+1)

for i in range(26):
	day[i].append(d+1)

#print(res)
#print(*t, sep="\n")
#print(score(t))
#print(*day, sep="\n")

for _ in range(int(input())):
	d, q = map(int, input().split())
	res += change(d-1, q-1)
	print(res)

Submission status: Accepted

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

L = 26
D = int(input())
C = list(map(int, input().split()))
S = [list(map(int, input().split())) for _ in range(D)]

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

M = int(input())

class BinaryIndexedTree:
    def __init__(self, n):
        self.n = n
        self.data = [0] * (self.n+1)
    
    def sum(self, i):
        res = 0
        while i > 0:
            res += self.data[i]
            i -= i & -i
        return res
    
    def add(self, i, x):
        if i <= 0: raise IndexError
        while i <= self.n:
            self.data[i] += x
            i += i & -i
    
    def lower_bound(self, x):
        if x <= 0: return 0
        cur, s, k = 0, 0, 1 << (self.n.bit_length()-1)
        while k:
            nxt = cur + k 
            if nxt <= self.n and s + self.data[nxt] < x:
                s += self.data[nxt]
                cur = nxt
            k >>= 1
        return cur + 1

def rsum(x):
    return x*(x+1)//2

b = [BinaryIndexedTree(D) for _ in range(L)]

score = 0
for d, cont in enumerate(T):
    cont -= 1
    b[cont].add(d+1, 1)
    score += S[d][cont]

for i in range(L):
    m = b[i].sum(D)
    tmp = 0
    s = [0]
    for j in range(1, m+1):
        s.append(b[i].lower_bound(j))
    s.append(D+1)

    for j in range(len(s)-1):
        x = s[j+1] - s[j] - 1
        tmp += rsum(x)
    
    score -= tmp*C[i]


def chg(d, q):
    diff = 0
    p = T[d]-1
    d += 1

    o = b[p].sum(d)
    d1 = b[p].lower_bound(o-1)
    d2 = b[p].lower_bound(o+1)

    diff += rsum(d-d1) * C[p]
    diff += rsum(d2-d) * C[p]
    diff -= rsum(d2-d1) * C[p]

    o = b[q].sum(d)
    d1 = b[q].lower_bound(o)
    d2 = b[q].lower_bound(o+1)

    diff += rsum(d2-d1) * C[q]
    diff -= rsum(d-d1) * C[q]
    diff -= rsum(d2-d) * C[q]

    b[p].add(d, -1)
    b[q].add(d, 1)

    d -= 1
    T[d] = q+1
    diff -= S[d][p]
    diff += S[d][q] 

    return diff

for _ in range(M):
    d, q = map(lambda x: int(x)-1, input().split())
    diff = chg(d, q)
    score += diff
    print(score)

Submission status: Accepted

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

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

N = 26


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

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


score = calc_score(t)


for di, qi in zip(d, q):
    # delete
    old_type = t[di]

    for next_d in range(di + 1, D):
        if t[next_d] == old_type:
            break
    else:
        next_d = D

    for prev_d in range(di - 1, -1, -1):
        if t[prev_d] == old_type:
            break
    else:
        prev_d = -1

    score -= s[di][old_type]
    score -= (next_d - di) * (di - prev_d) * c[old_type]

    # insert
    for next_d in range(di + 1, D):
        if t[next_d] == qi:
            break
    else:
        next_d = D

    for prev_d in range(di - 1, -1, -1):
        if t[prev_d] == qi:
            break
    else:
        prev_d = -1

    score += s[di][qi]
    score += (next_d - di) * (di - prev_d) * c[qi]

    print(score)

    t[di] = qi

Submission status: Accepted

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

Submission status: Accepted

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


def inpl():
    return list(map(int, input().split()))


def count_v(last_d, C, S, t, d):
    ret = S[t - 1]
    last_d[t - 1] = d
    for i in range(len(last_d)):
        ret -= C[i] * (d - last_d[i])
    return ret


def count_v_virtual(last_d, C, S, t, d):
    ret = S[t]
    tmp = last_d[t]
    last_d[t] = d
    for i in range(len(last_d)):
        ret -= C[i] * (d - last_d[i])
    last_d[t] = tmp
    return ret


def main():
    D = int(input())
    C = inpl()
    Ss = [inpl() for _ in range(D)]
    T = [int(input()) for _ in range(D)]
    M = int(input())
    DQ = [inpl() for _ in range(M)]
    last_d = [-1] * len(C)
    Contest = 26

    v = 0
    for d in range(D):
        tmp = count_v(last_d, C, Ss[d], T[d], d)
        v += tmp
        # print(v)

    for d, q in DQ:
        diff = 0
        original_t = T[d - 1]
        last_d_q = 0
        last_d_ori = 0
        for i in range(d):
            if T[i] == q:
                last_d_q = i + 1
            if T[i] == original_t and i < d - 1:
                last_d_ori = i + 1
        # print(d, q, original_t, last_d_q, last_d_ori)
        for i in range(d - 1, D):
            if T[i] == q:
                break
            diff += C[q - 1] * (d - last_d_q)
        # print(diff, C[q - 1])
        T[d - 1] = q
        for i in range(d - 1, D):
            if T[i] == original_t:
                break
            diff -= C[original_t - 1] * (d - last_d_ori)
        # print(C[original_t - 1], diff)
        v += diff + Ss[d - 1][q - 1] - Ss[d - 1][original_t - 1]
        print(v)
    return


if __name__ == '__main__':
    main()