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())#D=365
c = [0] + list(map(int, input().split()))#0<=c<=100
s = [0] + [[0] + list(map(int, input().split())) for _ in range(D)]#0<=s<=20000

t = [0] + [int(input()) for _ in range(D)]

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


held = [[0] for _ in range(27)]#選んだ日を保持
def culc_value(t):
    last = [0] * 27
    value = 0
    for d in range(1, D+1):
        type = t[d]
        held[type].append(d)
        value += s[d][type]
        last[type] = d
        for i in range(1, 27):
            value -= c[i] * (d - last[i])
    # 最終日+1 を追加、差分修正で前後見るときの後ろの最大値
    for i in range(1, 27):
        held[i].append(D+1)
    #print(held)
    return value


v_lastday = []
value = culc_value(t)

for d, q in dq:
    # 開催日の差分を修正
    value += - s[d][t[d]] + s[d][q]

    # dの前と後のq選択日のみ考えて、その間だけ修正する
    # 変換前のt[d-1]のマイナス計算を直す
    ind = held[t[d]].index(d)
    r = held[t[d]][ind+1]
    l = held[t[d]][ind-1]
    x = r - l
    value -= ((x + 1) * x // 2) * c[t[d]]
    y = d - l
    z = r - d
    value += (((y + 1) * y // 2) + (z + 1) * z // 2) * c[t[d]]

    del held[t[d]][ind]
    t[d] = q
    held[q].append(d)
    held[q] = sorted(held[q])
    #print(held[q])

    # 変換後のqのマイナス計算
    ind = held[q].index(d)
    r = held[q][ind+1]
    l = held[q][ind-1]
    x = r - l
    value += ((x + 1) * x // 2) * c[q]
    y = d - l
    z = r - d
    value -= (((y + 1) * y // 2) + (z + 1) * z // 2) * c[q]

    v_lastday.append(value)

for ans in v_lastday:
    print(ans)

Submission status: Accepted

Solution code:
import os
import sys

import numpy as np


def solve(inp):
    def bitree_sum(bit, t, i):
        s = 0
        while i > 0:
            s += bit[t, i]
            i ^= i & -i
        return s

    def bitree_add(bit, n, t, i, x):
        while i <= n:
            bit[t, i] += x
            i += i & -i

    def bitree_lower_bound(bit, n, d, t, x):
        sum_ = 0
        pos = 0
        for i in range(d, -1, -1):
            k = pos + (1 << i)
            if k <= n and sum_ + bit[t, k] < x:
                sum_ += bit[t, k]
                pos += 1 << i
        return pos + 1

    def initial_score(d, ccc, sss, ttt):
        bit_n = d + 3
        bit = np.zeros((26, bit_n), dtype=np.int64)
        INF = 10 ** 18
        for t in range(26):
            bitree_add(bit, bit_n, t, bit_n - 1, INF)

        last = np.full(26, -1, dtype=np.int64)
        score = 0

        for i in range(d):
            t = ttt[i]
            score += sss[i, t]
            for u in range(26):
                if u == t:
                    continue
                score -= ccc[u] * (i - last[u])
            last[t] = i
            bitree_add(bit, bit_n, t, i + 2, 1)

        return bit, score

    def update_score(bit, bit_n, bit_d, ccc, sss, ttt, d, q):
        diff = 0
        t = ttt[d]
        k = bitree_sum(bit, t, d + 2)
        c = bitree_lower_bound(bit, bit_n, bit_d, t, k - 1) - 2
        e = bitree_lower_bound(bit, bit_n, bit_d, t, k + 1) - 2
        b = ccc[t]
        diff -= b * (d - c) * (e - d)
        diff -= sss[d, t]

        k = bitree_sum(bit, q, d + 2)
        c = bitree_lower_bound(bit, bit_n, bit_d, q, k) - 2
        e = bitree_lower_bound(bit, bit_n, bit_d, q, k + 1) - 2
        b = ccc[q]
        diff += b * (d - c) * (e - d)
        diff += sss[d, q]

        return diff

    d = inp[0]
    ccc = inp[1:27]
    sss = np.zeros((d, 26), dtype=np.int64)
    for r in range(d):
        sss[r] = inp[27 + r * 26:27 + (r + 1) * 26]
    ttt = inp[27 + d * 26:27 + d * 27] - 1
    m = inp[27 + d * 27]
    ddd = inp[28 + d * 27::2] - 1
    qqq = inp[29 + d * 27::2] - 1

    bit, score = initial_score(d, ccc, sss, ttt)
    bit_n = d + 3
    bit_d = int(np.log2(bit_n))

    buf = np.zeros(m, dtype=np.int64)

    for i in range(m):
        cd = ddd[i]
        ct = qqq[i]
        diff = update_score(bit, bit_n, bit_d, ccc, sss, ttt, cd, ct)
        score += diff
        bitree_add(bit, bit_n, ttt[cd], cd + 2, -1)
        bitree_add(bit, bit_n, ct, cd + 2, 1)
        ttt[cd] = ct
        buf[i] = score

    return buf


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8[:],)')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8[:],)', cache=True)(solve)
    print('compiled', file=sys.stderr)

inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
ans = solve(inp)
print('\n'.join(map(str, ans)))

Submission status: Accepted

Solution code:
D = int(input())#D=365
c = [0] + list(map(int, input().split()))#0<=c<=100
s = [0] + [[0] + list(map(int, input().split())) for _ in range(D)]#0<=s<=20000

t = [0] + [int(input()) for _ in range(D)]

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


held = [[0] for _ in range(27)]
def culc_value(t):
    last = [0] * 27
    value = 0
    for d in range(1, D+1):
        type = t[d]
        held[type].append(d)
        value += s[d][type]
        last[type] = d
        for i in range(1, 27):
            value -= c[i] * (d - last[i])
    for i in range(1, 27):
        held[i].append(D+1)
    #print(held)
    return value


v_lastday = []
value = culc_value(t)

for d, q in dq:
    value += - s[d][t[d]] + s[d][q]

    # 変換前のt[d-1]のマイナス計算を直す
    ind = held[t[d]].index(d)
    r = held[t[d]][ind+1]
    l = held[t[d]][ind-1]
    x = r - l
    value -= ((x + 1) * x // 2) * c[t[d]]
    y = d - l
    z = r - d
    value += (((y + 1) * y // 2) + (z + 1) * z // 2) * c[t[d]]

    del held[t[d]][ind]
    t[d] = q
    held[q].append(d)
    held[q] = sorted(held[q])
    #print(held[q])

    # qに変換後のマイナス計算
    ind = held[q].index(d)
    r = held[q][ind+1]
    l = held[q][ind-1]
    x = r - l
    value += ((x + 1) * x // 2) * c[q]
    y = d - l
    z = r - d
    value -= (((y + 1) * y // 2) + (z + 1) * z // 2) * c[q]

    v_lastday.append(value)

for ans in v_lastday:
    print(ans)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_right


def calculate_score(c):
    global D, last, S
    rst = 0
    _last = last[c]
    for d in range(1, D + 1):
        down = C[c] * (d - _last[d])
        up = S[d][c] if _last[d] == d else 0
        rst += up - down
    return rst


Z = 26
D = int(input())
C = list(map(int, input().split()))

S = [tuple([0] * Z)] + [tuple(map(int, input().split())) for _ in range(D)]
T = [None] + [int(input()) - 1 for _ in range(D)] # 

M = int(input())
Q = [tuple(map(lambda x: int(x) - 1, s.split())) for s in sys.stdin.readlines()]


last = [[0] * (D + 1) for _ in range(Z)]  # last[i][d]
V = [0] * Z  # 各コンテストiごとの得点を保管しておく

# 初期状態でのlastを求める
for d in range(1, D + 1):
    t = T[d]
    for i in range(Z):
        last[i][d] = last[i][d - 1]
    last[t][d] = d
# 各コンテストiごとに得点を求める
for i in range(Z):
    V[i] = calculate_score(i)

# 初期状態での得点
score = sum(V)

for d, q in Q:
    d += 1  # Qだけ0-indexなので補正
    p = T[d]

    # d日目の開催が p -> q に変わる
    # まず, last[p]を更新する. 更新箇所はd日目 ~ 次の開催日直前
    e = bisect_right(last[p], d)
    for j in range(d, e):
        last[p][j] = last[p][j - 1]

    # 次に, last[q]を更新する. 更新箇所はd日目 ~ 次の開催日直前
    old = last[q][d]
    e = bisect_right(last[q], old)
    for j in range(d, e):
        last[q][j] = d

    # まず, 変更前のp, qの値を引く
    score -= V[p] + V[q]

    # 変更後のp, qの値を計算し, 全体に足す
    V[p] = calculate_score(p)
    V[q] = calculate_score(q)
    score += V[p] + V[q]
    print(score)

    # Tを更新
    T[d] = q

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_right, bisect_left


def calculate_score(c):
    global D, last, S
    rst = 0
    _last = last[c]
    for d in range(1, D + 1):
        down = C[c] * (d - _last[d])
        up = S[d][c] if _last[d] == d else 0
        rst += up - down
    return rst


Z = 26
D = int(input())
C = list(map(int, input().split()))

S = [tuple([0] * Z)] + [tuple(map(int, input().split())) for _ in range(D)]
T = [None] + [int(input()) - 1 for _ in range(D)] # 

M = int(input())
Q = [tuple(map(lambda x: int(x) - 1, s.split())) for s in sys.stdin.readlines()]


last = [[0] * (D + 1) for _ in range(Z)]  # last[i][d]
V = [0] * Z  # 各コンテストiごとの得点を保管しておく

# 初期状態でのlastを求める
for d in range(1, D + 1):
    t = T[d]
    for p in range(Z):
        last[p][d] = last[p][d - 1]
    last[t][d] = d
# 各コンテストpごとに得点を求める
for p in range(Z):
    V[p] = calculate_score(p)

# 初期状態での得点
score = sum(V)

for d, q in Q:
    d += 1  # Qだけ0-indexなので補正
    p = T[d]

    # d日目の開催が p -> q に変わる
    # まず, last[p]を更新する. 更新箇所はd日目 ~ 次の開催日直前
    e = bisect_right(last[p], d)
    for j in range(d, e):
        last[p][j] = last[p][j - 1]

    # 次に, last[q]を更新する. 更新箇所はd日目 ~ 次の開催日直前
    old = last[q][d]
    e = bisect_right(last[q], old)
    for j in range(d, e):
        last[q][j] = d

    score -= V[p] + V[q]
    V[p] = calculate_score(p)
    V[q] = calculate_score(q)
    score += V[p] + V[q]
    print(score)

    T[d] = q

Submission status: Accepted

Solution code:
def f(a,d,T):
    try:
        return T[d:].index(a)+d
    except ValueError:
        return len(T)

from random import randint
A=26

D=int(input())

C=[0]+list(map(int,input().split())) #減る満足度のベース
S=[0]*(D+1) #S[d][i] :(d+1)日目にコンテストiを開催した時の満足度

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

T=[0]
for i in range(D):
    T.append(int(input()))

L=[[0]*(A+1) for _ in range(D+1)]

for x in range(1,D+1):
    t=T[x]
    for j in range(1,A+1):
        if t!=j:
            L[x][j]=L[x-1][j]+1
        else:
            L[x][j]=0
            
X=0
for d in range(1,D+1):
    X+=S[d][T[d]]    
    for j in range(1,A+1):
        X-=C[j]*L[d][j]

M=int(input())
for _ in range(M):
    d,q=map(int,input().split())
    p=T[d]

    a=f(p,d+1,T)
    b=f(q,d+1,T)
    
    Y=0
    h=L[d-1][p]
    for i in range(d,a):
        h+=1
        Y+=h-L[i][p]
        L[i][p]=h
        
    m=0
    Z=0
    for j in range(d,b):
        Z-=m-L[j][q]
        L[j][q]=m
        m+=1

    X+=(S[d][q]-S[d][p])+Z*C[q]-Y*C[p]
    print(X)

    T[d]=q

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_right, bisect_left


def checkScore(p):
    global D, last, S
    rst = 0
    _last = last[p]
    for d in range(1, D + 1):
        down = C[p] * (d - _last[d])
        up = S[d][p] if _last[d] == d else 0
        rst += up - down
    return rst


Z = 26
D = int(input())
C = list(map(int, input().split()))
S = [tuple([0] * Z)] + [tuple(map(int, input().split())) for _ in range(D)]
T = [None] + [int(input()) - 1 for _ in range(D)]

M = int(input())
Q = [tuple(map(lambda x: int(x) - 1, s.split())) for s in sys.stdin.readlines()]


last = [[0] * (D + 1) for _ in range(Z)]
V = [0] * Z
for d in range(1, D + 1):
    t = T[d]
    for p in range(Z):
        last[p][d] = last[p][d - 1]
    last[t][d] = d
for p in range(Z):
    V[p] = checkScore(p)

score = sum(V)

for d, q in Q:
    d += 1

    p = T[d]
    s = bisect_left(last[p], d)
    e = bisect_right(last[p], d)
    for j in range(s, e):
        last[p][j] = last[p][j - 1]

    old = last[q][d]
    e = bisect_right(last[q], old)
    for j in range(d, e):
        last[q][j] = d

    score -= V[p] + V[q]
    V[p] = checkScore(p)
    V[q] = checkScore(q)
    score += V[p] + V[q]
    print(score)

    T[d] = q

Submission status: Accepted

Solution code:

import time
import random
import collections
import bisect  

start = time.time()

def insert(list, n): 
    bisect.insort(list, n)  
    return list

def read_input():
  D = int(input())
  c = list(map(int, input().split()))
  s = [list(map(int, input().split())) for _ in range(D)]
  return D, c, s
D, c, s = read_input()

tests = [int(input()) - 1 for _ in range(D)]
M = int(input())
d = [list(map(lambda x:int(x)-1, input().split())) for _ in range(M)]

#c = np.array(c)
#s = np.array(s)
#tests = np.argmax(s, axis=1)

def get_dates_for_tests(tests):
  dates_for_tests = [list([-1]) for _ in range(26)]
  for i, t in enumerate(tests):
    dates_for_tests[t].append(i)
  for t in range(26):
    dates_for_tests[t].append(D)
  return dates_for_tests

dates_for_tests = get_dates_for_tests(tests)

def get_score(tests):
  dates_for_tests = get_dates_for_tests(tests)
  score = 0
  d = [0]*26 #np.zeros(26, dtype=np.int64)
  for selected, S in zip(tests, s):
    d = [x+1 for x in d]#d += 1
    d[selected] = 0
    score += S[selected]
    for ct, dt in zip(c,d):
      score -= ct*dt# - (c * d).sum()
  return score

def score_diff(date, test):
  #print(date, test)
  before = tests[date]
  if test == before:
    return 0, None, None
  pos_diff = s[date][test] - s[date][before]
  new_index = bisect.bisect_left(dates_for_tests[test], date, 1)
  new_diff = c[test] * (dates_for_tests[test][new_index] - date) * (date - dates_for_tests[test][new_index-1])

  old_index = bisect.bisect_left(dates_for_tests[before], date, 1)
  #print(c[test], dates_for_tests[test])
  #print(c[before], dates_for_tests[before])
  old_diff = c[before] * (dates_for_tests[before][old_index+1] - date) * (date - dates_for_tests[before][old_index-1])
  
  total_diff = pos_diff + new_diff - old_diff
  #print(test, total_diff, pos_diff, new_diff, -old_diff)
  return total_diff, new_index, old_index

current_score = get_score(tests)
#print(d)
for date, test in d:
  total_diff, new_index, old_index= score_diff(date, test)
  current_score += total_diff
  del dates_for_tests[tests[date]][old_index]
  insert(dates_for_tests[test], date)
  tests[date] = test
  
  print(current_score)

Submission status: Accepted

Solution code:
import sys


def B(T):
    global S, Z, D
    _last = [0] * Z
    cnt = 0
    for d in range(1, D + 1):
        t = T[d]
        _last[t] = d
        up = S[d][t]
        down = sum(C[i] * (d - _last[i]) for i in range(Z))
        cnt += up - down
    return cnt


def checkScore(r):
    global D, last
    L = last[r]
    rst = 0
    for d in range(1, D + 1):
        down = C[r] * (d - L[d])
        up = S[d][r] if L[d] == d else 0
        rst += up - down
    return rst


Z = 26
D = int(input())
C = list(map(int, input().split()))
S = [tuple([0] * Z)]
S += [tuple(map(int, input().split())) for _ in range(D)]
T = [None] + [int(input()) - 1 for _ in range(D)]

M = int(input())
Q = [tuple(map(lambda x: int(x) - 1, s.split())) for s in sys.stdin.readlines()]


last = [[0] * (D + 1) for _ in range(Z)]
V = [0] * Z
for d in range(1, D + 1):
    t = T[d]
    for p in range(Z):
        last[p][d] = last[p][d - 1]
    last[t][d] = d
for p in range(Z):
    V[p] = checkScore(p)

score = sum(V)

for d, q in Q:
    d += 1

    p = T[d]
    T[d] = q

    for r, L in ((p, last[p]), (q, last[q])):
        for e in range(1, D + 1):
            L[e] = L[e - 1] if r != T[e] else e

    score -= V[p] + V[q]
    V[p] = checkScore(p)
    V[q] = checkScore(q)
    score += V[p] + V[q]
    # # if M > 10 ** 4:
    #     print(score)
    # else:
    #     print(B(T))
    print(score)

Submission status: Accepted

Solution code:
import numpy as np
import time
import random
import collections
import bisect  

start = time.time()

def insert(list, n): 
    bisect.insort(list, n)  
    return list

def read_input():
  D = int(input())
  c = list(map(int, input().split()))
  s = [list(map(int, input().split())) for _ in range(D)]
  return D, c, s
D, c, s = read_input()

tests = [int(input()) - 1 for _ in range(D)]
M = int(input())
d = [list(map(lambda x:int(x)-1, input().split())) for _ in range(M)]

c = np.array(c)
s = np.array(s)
#tests = np.argmax(s, axis=1)

def get_dates_for_tests(tests):
  dates_for_tests = [list([-1]) for _ in range(26)]
  for i, t in enumerate(tests):
    dates_for_tests[t].append(i)
  for t in range(26):
    dates_for_tests[t].append(D)
  return dates_for_tests

dates_for_tests = get_dates_for_tests(tests)

def get_score(tests):
  dates_for_tests = get_dates_for_tests(tests)
  score = 0
  d = np.zeros(26, dtype=np.int64)
  for selected, S in zip(tests, s):
    d += 1
    d[selected] = 0
    score += S[selected] - (c * d).sum()
  return score

def score_diff(date, test):
  #print(date, test)
  before = tests[date]
  if test == before:
    return 0, None, None
  pos_diff = s[date, test] - s[date, before]
  new_index = bisect.bisect_left(dates_for_tests[test], date, 1)
  new_diff = c[test] * (dates_for_tests[test][new_index] - date) * (date - dates_for_tests[test][new_index-1])

  old_index = bisect.bisect_left(dates_for_tests[before], date, 1)
  #print(c[test], dates_for_tests[test])
  #print(c[before], dates_for_tests[before])
  old_diff = c[before] * (dates_for_tests[before][old_index+1] - date) * (date - dates_for_tests[before][old_index-1])
  
  total_diff = pos_diff + new_diff - old_diff
  #print(test, total_diff, pos_diff, new_diff, -old_diff)
  return total_diff, new_index, old_index

current_score = get_score(tests)
#print(d)
for date, test in d:
  total_diff, new_index, old_index= score_diff(date, test)
  current_score += total_diff
  del dates_for_tests[tests[date]][old_index]
  insert(dates_for_tests[test], date)
  tests[date] = test
  
  print(current_score)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

D = INT()
C = LIST()
s = [LIST() for _ in range(D)]
t = [INT() for _ in range(D)]

## 1回最終スコアを計算する
score = [0]*26
last = [0]*26
now = 0
for i in range(D):  # i+1日目
    score[t[i]-1] += s[i][t[i]-1]
    last[t[i]-1] = i+1
    for j in range(26):
        score[j] -= C[j]*(i+1-last[j])

now = sum(score)
M = INT()

ans = [0]*M
for i in range(M):  # nowからの差分を考える
    d, q = MAP()  # q:更新後
    d -= 1
    q -= 1
    c = t[d]-1  # c:更新前
    t[d] = q+1
    last_c = 0
    last_q = 0
    score_c = 0
    score_q = 0
    for j in range(D):
        if t[j]-1 == c:
            last_c = j+1
            score_c += s[j][c]
        elif t[j]-1 == q:
            last_q = j+1
            score_q += s[j][q]
        score_c -= C[c] * (j+1 - last_c)
        score_q -= C[q] * (j+1 - last_q)
    now += -score[c]-score[q]+score_c+score_q
    score[c] = score_c
    score[q] = score_q
    ans[i] = now

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

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

def init():
    global T, days
    score = 0
    last = [0] * 26
    for d, t in enumerate(T, 1):
        score += S[d - 1][t - 1]
        last[t - 1] = d
        for c, l in zip(C, last): score -= c * (d - l)
        days[t - 1].append(d)
    for i in range(26): days[i].append(D+1)
    return score

def diff(d, q):
    global score, T, C, S, days
    p = T[d - 1]
    score += S[d - 1][q - 1] - S[d - 1][p - 1]
    idx_p = bisect_left(days[p - 1], d)
    bef_p, aft_p = days[p - 1][idx_p - 1], days[p - 1][idx_p + 1]
    del days[p - 1][idx_p]
    idx_q = bisect_left(days[q - 1], d)
    bef_q, aft_q = days[q - 1][idx_q - 1], days[q - 1][idx_q]
    days[q - 1].insert(idx_q, d)
    score += C[q - 1] * (d - bef_q) * (aft_q - d) - C[p - 1] * (d - bef_p) * (aft_p - d)
    T[d - 1] = q
    return score
    
score = init()
M = int(input())
for _ in range(M):
    d, q = map(int, input().split())
    print(diff(d, q))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from bisect import bisect
from bisect import bisect_right
from bisect import bisect_left
from bisect import insort
from bisect import insort_right
from bisect import insort_left 

def scores(c, s, t, t_days):
    last = [0] * 26
    D = len(t)
    t_score = []
    # print([s[d*26+i] for d, i in enumerate(t)])
    s_score = sum([s[d*26+i] for d, i in enumerate(t)])
    for i, days in enumerate(t_days):
        last = 0
        score = 0
        for d in days[1:]:
            delta = d - last - 1
            # print(i, d, delta)
            score += delta * (delta + 1)
            last = d
        # print(i, score)
        score = score * c[i] // 2
        t_score.append(score)
    # print(t_score)
    return s_score - sum(t_score)


def main():
    D, *cs = map(int, read().split())
    c = cs[:26]
    se = 26+26*D
    s = cs[26:se]
    te = se+D
    t = [x-1 for x in cs[se:te]]
    M = cs[te]
    dq = [(d, q-1) for d, q in zip(cs[te+1::2], cs[te+2::2])]

    t_days = [[0] for i in range(26)]
    for d, x in enumerate(t, start=1):
        t_days[x].append(d)
    for i in range(26):
        t_days[i].append(D+1)
    # print(t_days)

    v = scores(c, s, t, t_days)
    # print(v)
    ans = []
    for d, q in dq:
        dd = d-1
        bq = t[dd]
        t[dd] = q
        v += s[dd*26+q] - s[dd*26+bq]
        days_q = t_days[q]
        days_bq = t_days[bq]
        qi = bisect_left(days_q, d)
        bqi = bisect_left(days_bq, d)
        # print(bq, bqi, q, qi)

        # 削除することで増える分
        da = days_bq[bqi+1] - days_bq[bqi-1] - 1
        db1 = days_bq[bqi+1] - days_bq[bqi] - 1
        db2 = days_bq[bqi] - days_bq[bqi-1] - 1
        bqp = da * (da + 1) - (db1*(db1+1) + db2*(db2+1))
        # 追加することで減る分
        db = days_q[qi] - days_q[qi-1] - 1
        da1 = days_q[qi] - d - 1
        da2 = d - days_q[qi-1] - 1
        qp = db * (db + 1) - (da1*(da1+1) + da2*(da2+1))

        # print((bqp * c[bq] // 2))
        # print((qp * c[q] // 2))
        delta = (qp * c[q] // 2) - (bqp * c[bq] // 2)

        # print(days_bq, days_q)
        insort_left(days_q, d)
        del(days_bq[bqi])
        # print(days_bq, days_q)
        v += delta
        # print(v, delta)
        ans.append(v)
        # t_days[bq].remove(bq)

        # qの不満度が減る分



        # last = 0
        # score = 0
        # for d in t_days[q] + [D+1]:
        #     delta = d - last - 1
        #     # print(i, d, delta)
        #     score += delta * (delta + 1)
        #     last = d
        # # print(i, score)
        # score = score * c[q] // 2


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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys


def read():
    return sys.stdin.readline().rstrip()


def main():
    d = int(read())
    c = [int(i) for i in read().split()]
    s = [[int(i) for i in read().split()] for _ in range(d)]
    t = [int(read()) - 1 for _ in range(d)]
    m = int(read())
    query = [[int(i) - 1 for i in read().split()] for _ in range(m)]
    score = 0
    last = [[0] * 26 for _ in range(d)]
    for i in range(d):
        score += s[i][t[i]]
        if i > 0:
            last[i] = last[i - 1].copy()
        last[i][t[i]] = i + 1
        for j in range(26):
            score -= c[j] * (i + 1 - last[i][j])
    for di, qi in query:
        hi = t[di]
        t[di] = qi
        score -= s[di][hi]
        score += s[di][qi]
        if di == 0:
            last[di][hi] = 0
        else:
            last[di][hi] = last[di - 1][hi]
        score -= c[hi] * (di + 1 - last[di][hi])
        score += c[qi] * (di + 1 - last[di][qi])
        last[di][qi] = di + 1
        for i in range(di + 1, d):
            score += c[hi] * (i + 1 - last[i][hi])
            if t[i] != hi:
                last[i][hi] = last[i - 1][hi]
                score -= c[hi] * (i + 1 - last[i][hi])
            else:
                break
        for i in range(di + 1, d):
            score += c[qi] * (i + 1 - last[i][qi])
            if t[i] != qi:
                last[i][qi] = last[i - 1][qi]
                score -= c[qi] * (i + 1 - last[i][qi])
            else:
                break
        print(score)


if __name__ == '__main__':
    main()