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:
NTEST = 26

D=int(input())

C=list(map(int,input().split()))

SL=list()
SL.append([0 for i in range(NTEST)])
for d in range(D):
    S=list(map(int,input().split()))
    SL.append(S)

tests=list()
tests.append(0)
for d in range(D):
    tests.append(int(input()))

def calcSat(test_applied):
    lastDay = [0 for i in range(NTEST)]

    sat = 0
    for d in range(1,D+1):
        tst = test_applied[d] - 1
        lastDay[tst] = d
        sat += SL[d][tst]
        for itst in range(NTEST):
            sat -= C[itst] * (d-lastDay[itst])
    return sat

satList = list()
satList.append(0)
lastDay = [[0 for i in range(NTEST)]]

def calcSat_with_memo(test_applied):

    total_sat = 0
    for d in range(1,D+1):
        lastDay.append(list(lastDay[d-1]))
        sat = 0
        tst = test_applied[d] - 1
        lastDay[d][tst] = d
        sat += SL[d][tst]
        for itst in range(NTEST):
            sat -= C[itst] * (d-lastDay[d][itst])
        satList.append(sat)
        total_sat += sat

    return total_sat

def recalcSat_with_memo(total_sat_before, tday, t_from, t_to, test_applied):

    d_total_sat = 0

    lastDay[tday][t_from -1]=lastDay[tday-1][t_from -1]
    d_sat=0
    d_sat += (SL[tday][t_to -1]-SL[tday][t_from -1])
    d_sat += C[t_to -1]*(tday - lastDay[tday][t_to -1])
    d_sat -= C[t_from -1]*(tday - lastDay[tday][t_from -1])

    lastDay[tday][t_to -1]=tday

    satList[tday]+= d_sat
    d_total_sat  += d_sat

    old_last = tday
    new_last = lastDay[tday][t_from -1]
    for d in range(tday+1,D+1):
        if test_applied[d] == t_from :
            break
        d_sat = C[t_from -1]*(- old_last + new_last)
        lastDay[d][t_from -1] = new_last
        satList[d]+= d_sat
        d_total_sat += d_sat

    old_last = lastDay[tday-1][t_to -1]
    new_last = tday
    for d in range(tday+1,D+1):
        if test_applied[d] == t_to :
            break
        d_sat = C[t_to -1]*(- old_last + new_last)
        lastDay[d][t_to -1] = new_last
        satList[d]+= d_sat
        d_total_sat += d_sat
            
    return d_total_sat


# sat = calcSat(tests)
# print(sat)

sat = calcSat_with_memo(tests)
print(sat)


# -------------------
M=int(input())

ans = list()

for m in range(M):
    d, new_tst = list(map(int, input().split()))

    d_sat = recalcSat_with_memo(sat, d, tests[d], new_tst, tests)

    tests[d] = new_tst
    sat += d_sat
    ans.append(sat)

for m in range(M):
    print(ans[m])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(300000)
from collections import defaultdict

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI0(): return map(lambda s: int(s) - 1, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
def LMI0(): return list(map(lambda s: int(s) - 1, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')


D = I()
C = LMI()
S = [LMI() for _ in range(D)]
T = [I() - 1 for _ in range(D)]
M = I()

last = [[i + 1] * 26 for i in range(D)]
for d in range(D):
    i = T[d]
    j = 0
    for dd in range(d, D):
        # if last[dd][i] == 0:
        #     continue
        # contrib += last[dd][i] - j
        last[dd][i] = j
        j += 1

def eval3(d, q):
    i = T[d]
    val = S[d][q] - S[d][i]

    contrib = 0
    if d == 0:
        j = 1
    else:
        j = last[d - 1][i] + 1
    for dd in range(d, D):
        if dd > d and last[dd][i] == 0:
            continue
        contrib += j - last[dd][i]
        last[dd][i] = j
        j += 1
    val -= contrib * C[i]

    contrib = 0
    j = 0
    for dd in range(d, D):
        if last[dd][q] == 0:
            continue
        contrib += last[dd][q] - j
        last[dd][q] = j
        j += 1
    val += contrib * C[q]

    T[d] = q

    return val

# def eval2(T):
#     last = defaultdict(int)
#     ans = 0
#     for d in range(D):
#         ans += S[d][T[d]]
#         ans -= Csum * (d + 1)
#
#         ans += passed * C[T[d]]
#         last[T[d]] = d + 1
#     return ans
#
def score0(T):
    last = defaultdict(int)
    ans = 0
    for d in range(D):
        ans += S[d][T[d]]
        last[T[d]] = d + 1
        for i in range(26):
            ans -= C[i] * (d + 1 - last[i])
    return ans


score = score0(T)
for d, q in [tuple(MI0()) for _ in range(M)]:
    val = eval3(d, q)
    score += val
    print(score)

Submission status: Wrong Answer

Solution code:
D = int(input())
C = list(map(int ,input().split()))
S = [list(map(int, input().split())) for i in range(D)]
sumc = sum(C)
last = [0 for i in range(26)]
check = [0 for i in range(26)]
con = []

ans = 0
for i in range(D):
    t = int(input())
    last[t-1] = i+1
    ans += S[i][t-1]
    check[t-1] += 1
    con.append(t)
    for j in range(26):
        ans -= C[j]*(i+1 - last[j])

M = int(input())
for i in range(M):
    d, q = map(int, input().split())
    e = con[d-1] #i日目にやるコンテスト
    l1 = 0
    l2 = 0
    tmpe = 0
    tmpq = 0
    f1 = D
    f2 = D
    for j in range(D):
        if check[e-1] == 0 and check[q-1] == 0:
            break
        if tmpe == 0 and tmpq == 0:
            break
        if j < d-1:
            if con[j] == e:
                l1 = j #変更前のコンテストを直前の最後にいつやったか
            if con[j] == q:
                l2 = j #変更後のコンテストを直前の最後にいつやったか
        if j > d-1:
            if con[j] == e and tmpe == 0:
                f1 = j #変更前のコンテストを直後にいつやったか
                tmpe = 1
            if con[j] == q and tmpq == 0:
                f2 = j #変更後のコンテストを直後にいつやったか
                tmpq = 1
    con[d-1] = q
    check[e-1] -= 1
    check[q-1] += 1
    ans = ans - S[d-1][e-1] + S[d-1][q-1] + C[q-1]*(f2-d+1)*(d-l2-1) - C[e-1]*(f1-d+1)*(d-l1-1)
    print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

D=int(input())
*c,=map(int,input().split())
c=np.array(c,dtype=int)
s=[]
for i in range(D):
    *x,=map(int,input().split())
    s.append(x)

s=np.array(s,dtype=int).reshape((D,26))
dt=[]
cnt=np.array([0]*26)

for d in range(D):
    x=s[d]-c*(d-cnt)
    y=np.argmax(x)
    cnt[y]=d+1
    dt.append(y+1)

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

v0=score(dt)
newt=dt+[]

import random

for _ in range(1):
    for d in range(D):
        q=0
        while True:
            q=random.randint(1,26)
            if q!=newt[d]: break
        newt[d]=q
        v=score(newt)
        if v>v0:
            dt=newt
            v0=v
        else:
            newt=dt+[]
for i in dt:
    print(i)

Submission status: Wrong Answer

Solution code:
# モジュールのインポート
import numpy as np

# 標準入力を取得
D = int(input())
c = list(map(int, input().split()))
s = []
for d in range(D):
    s_d = list(map(int, input().split()))
    s.append(s_d)
t = []
for d in range(D):
    t_d = int(input())
    t.append(t_d)
M = int(input())
d, q = [], []
for m in range(M):
    d_m, q_m = list(map(int, input().split()))
    d.append(d_m)
    q.append(q_m)

c = np.array(c)
s = np.array(s)
t = np.array(t)
d = np.array(d)
q = np.array(q)

# 求解処理
# 初期コスト計算


def cost(t: np.ndarray) -> int:
    KIND = 26
    last = np.array([0 for i in range(KIND)])
    S = 0
    for day in range(1, D + 1):
        index_day = day - 1
        index_t_day = t[index_day] - 1
        S += s[index_day][index_t_day]
        last[index_t_day] = day
        S -= sum(c * (day - last))
    return S


S = cost(t)
for d_m, q_m in zip(d, q):
    index_d_m = d_m - 1
    t_d_m = t[index_d_m]
    index_t_d_m = t_d_m - 1
    index_q_m = q_m - 1
    # 増加処理の修正
    S = S - s[index_d_m][index_t_d_m] + s[index_d_m][index_q_m]
    # 減少処理の修正
    c_t_d_m = c[index_t_d_m]
    c_q_m = c[index_q_m]
    last_t_d_m = 0
    last_q_m = 0
    for day in range(d_m, D + 1):
        index_day = day - 1
        t_day = t[index_day]
        if t_day == t_d_m:
            last_t_d_m = day
        if t_day == q_m:
            last_q_m = day
        S = S + c_t_d_m * (day - last_t_d_m) + c_q_m * (day - last_q_m)

    t[index_d_m] = q_m
    last_t_d_m = 0
    last_q_m = 0
    for day in range(d_m, D + 1):
        index_day = day - 1
        t_day = t[index_day]
        if t_day == t_d_m:
            last_t_d_m = day
        if t_day == q_m:
            last_q_m = day
        S = S - c_t_d_m * (day - last_t_d_m) - c_q_m * (day - last_q_m)
    print(S)

Submission status: Wrong Answer

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

h=0
last=[-1]*26

for i in range(D):
    h+=s[i][t[i]-1]
    last[t[i]-1]=i
    for j in range(26):
        h-=c[j]*(i-last[j])

m=int(input())
for _ in range(m):
    d,q=map(int,input().split())
    h+=s[d-1][q-1]-s[d-1][t[d-1]-1]
    o=t[d-1]
    t[d-1]=q

    pre=1
    for i in range(d-2,-1,-1):
        if t[i]==o:
            break
        pre+=1
    post=1
    for j in range(d,D):
        if t[i]==o:
            break
        post+=1
    h-=c[o-1]*pre*post

    pre = 1
    for i in range(d - 2, -1, -1):
        if t[i] == q:
            break
        pre += 1
    post = 1
    for j in range(d, D):
        if t[i] == q:
            break
        post += 1
    h += c[q - 1] * pre * post

    print(h)

Submission status: Wrong Answer

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]
        bitree_add(bit, bit_n, t, d + 2, -1)
        k = bitree_sum(bit, t, d + 1)
        c = bitree_lower_bound(bit, bit_n, bit_d, t, k) - 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]

        ttt[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 + 2
    bit_d = int(np.log2(bit_n))

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

    for i in range(m):
        diff = update_score(bit, bit_n, bit_d, ccc, sss, ttt, ddd[i], qqq[i])
        score += diff
        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: Wrong Answer

Solution code:
import numpy as np
from sys import argv
import time


def input_from_file():
    with open(argv[1], "r") as f:
        D = int(f.readline())
        C = np.array(f.readline().split(), dtype=int)
        S = tuple(tuple(map(int, f.readline().split())) for _ in range(D))
    return D, C, S


def input_from_console():
    D = int(input())
    C = np.array(input().split(), dtype=int)
    S = tuple(tuple(map(int, input().split())) for _ in range(D))
    return D, C, S


def greed(D, C, S):
    last = np.ones(26, dtype=int)
    ans = []
    for s in S:
        s = np.array(s)
        tmp = s + C * last
        i = np.argmax(tmp)
        last[i] = 0
        last += 1
        ans.append(i + 1)
    return ans


def calc_score(D, C, S, T):
    res = 0
    last = np.ones(26, dtype=int)
    for d, t in enumerate(T):
        t -= 1
        last[t] = 0
        score = S[d][t]
        score -= (C * last).sum()
        res += score
        last += 1
    return res


def output_to_file(ans):
    with open("output.txt", "w", newline="") as f:
        for a in ans:
            f.write("{}\n".format(a))


def main():
    start = time.time()
    lim = 1.800
    D, C, S = input_from_console()
    #D, C, S = input_from_file()
    #初期解, 貪欲法
    sol = greed(D, C, S)
    score = calc_score(D, C, S, sol)
    while True:
        d = np.random.randint(0, D//2)
        q = np.random.randint(1, 27)
        old = sol[d]
        sol[d] = q
        new_score = calc_score(D, C, S, sol)
        if new_score > score:
            score = new_score
        else:
            sol[d] = old
        if time.time() - start >= lim:
            break
    print(*sol, sep="\n")
    # output_to_file(sol)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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 + 2
        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 + 1, 1)

        return bit, score

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

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

        ttt[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 + 2
    bit_d = int(np.log2(bit_n))

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

    for i in range(m):
        diff = update_score(bit, bit_n, bit_d, ccc, sss, ttt, ddd[i], qqq[i])
        score += diff
        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: Wrong Answer

Solution code:
from bisect import bisect_right, bisect_left
# instead of AVLTree
class BITbisect():
    def __init__(self, InputProbNumbers):
        # 座圧
        self.ind_to_co = [-10**18]
        self.co_to_ind = {}
        for ind, num in enumerate(InputProbNumbers):
            self.ind_to_co.append(num)
            self.co_to_ind[num] = ind+1
        self.max = len(self.co_to_ind)
        self.data = [0]*(self.max+1)
    
    def __str__(self):
        retList = []
        for i in range(1, self.max+1):
            x = self.ind_to_co[i]
            if self.count(x):
                c = self.count(x)
                for _ in range(c):
                    retList.append(x)
        return "[" + ", ".join([str(a) for a in retList]) + "]"
    
    def __getitem__(self, key):
        key += 1
        s = 0
        ind = 0
        l = self.max.bit_length()
        for i in reversed(range(l)):
            if ind + (1<<i) <= self.max:
                if s + self.data[ind+(1<<i)] < key:
                    s += self.data[ind+(1<<i)]
                    ind += (1<<i)
        if ind == self.max or key < 0:
            raise IndexError("BIT index out of range")
        return self.ind_to_co[ind+1]
    
    def __len__(self):
        return self._query_sum(self.max)
    
    def __contains__(self, num):
        if not num in self.co_to_ind:
            return False
        return self.count(num) > 0
    
    # 0からiまでの区間和
    # 左に進んでいく
    def _query_sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    # i番目の要素にxを足す
    # 上に登っていく
    def _add(self, i, x):
        while i <= self.max:
            self.data[i] += x
            i += i & -i
    
    # 値xを挿入
    def push(self, x):
        if not x in self.co_to_ind:
            raise KeyError("The pushing number didnt initialized")
        self._add(self.co_to_ind[x], 1)
            
    # 値xを削除
    def delete(self, x):
        if not x in self.co_to_ind:
            raise KeyError("The deleting number didnt initialized")
        if self.count(x) <= 0:
            raise ValueError("The deleting number doesnt exist")
        self._add(self.co_to_ind[x], -1)

    # 要素xの個数
    def count(self, x):
        return self._query_sum(self.co_to_ind[x]) - self._query_sum(self.co_to_ind[x]-1)
    
    # 値xを超える最低ind
    def bisect_right(self, x):
        if x in self.co_to_ind:
            i = self.co_to_ind[x]
        else:
            i = bisect_right(self.ind_to_co, x) - 1
        return self._query_sum(i)

    # 値xを下回る最低ind
    def bisect_left(self, x):
        if x in self.co_to_ind:
            i = self.co_to_ind[x]
        else:
            i = bisect_left(self.ind_to_co, x)
        if i == 1:
            return 0
        return self._query_sum(i-1)

import sys
input = sys.stdin.readline

Days = int(input())
C = list(map(int, input().split())) # 満足度低下
Ss = [list(map(int, input().split())) for _ in range(Days)]
# Ss[d][i]: d日目にiを開催したときの満足度
T = [int(input()) for _ in range(Days)] # 開催するコンテスト
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]

INF = 10**18

def outputToScore(T):
    last = [0]*26
    used = [BITbisect(list(range(Days+1))) for _ in range(26)]
    satisfied = 0
    for d, t in enumerate(T):
        t -= 1; d += 1
        satisfied += Ss[d-1][t]
        used[t].push(d)
        last[t] = d
        for i, c in enumerate(C):
            satisfied -= c*(d-last[i])
        # print(satisfied)
    return satisfied, used

Satisfied, Used = outputToScore(T)
for d, aft in Query:
    aft -= 1
    bef = T[d-1]-1
    deltaSatis = Ss[d-1][aft] - Ss[d-1][bef]
    # d日目のコンテストをbefからaftに変える
    befind = Used[bef].bisect_left(d)
    aftind = Used[aft].bisect_left(d)
    # print(d)
    # print(Used[bef], bef)
    # print(Used[aft], aft)
    # bi-1 -> bi -> bi+1 を bi-1 -> bi+1
    befday0 = 0
    befday2 = Days+1
    if befind > 0:
        befday0 = Used[bef][befind-1]
    if befind < len(Used[bef])-1:
        befday2 = Used[bef][befind+1]
    befd01 = d - befday0
    befd12 = befday2 - d
    befd02 = befday2-befday0
    deltaSatis -= C[bef]*(befd02*(befd02-1)//2) - C[bef]*(befd01*(befd01-1)//2 + befd12*(befd12-1)//2)

    # ai -> ai+1 を ai -> (insert) -> ai+1
    if len(Used[aft]) > 0:
        aftday0 = 0
        aftday2 = Days+1
        if aftind < len(Used[aft])-1:
            aftday2 = Used[aft][aftind]
        if aftind > 0:
            aftday0 = Used[aft][aftind-1]
        aftd01 = d - aftday0
        aftd12 = aftday2 - d
        aftd02 = aftd01 + aftd12
        deltaSatis += C[aft]*(aftd02*(aftd02-1)//2) - C[aft]*(aftd01*(aftd01-1)//2 + aftd12*(aftd12-1)//2)
    else:
        d01 = d
        d12 = Days+1 - d
        deltaSatis += C[aft] * Days*(Days+1)//2 - C[aft]*(d01*(d01-1)//2 + d12*(d12-1)//2)

    Used[bef].delete(d)
    Used[aft].push(d)
    T[d-1] = aft+1
    Satisfied += deltaSatis
    print(Satisfied)

Submission status: Wrong Answer

Solution code:
D = int(input())
C = list(map(int ,input().split()))
S = [list(map(int, input().split())) for i in range(D)]
sumc = sum(C)
last = [0 for i in range(26)]
con = []

ans = 0
for i in range(D):
    t = int(input())
    last[t-1] = i+1
    ans += S[i][t-1]
    con.append(t)
    for j in range(26):
        ans -= C[j]*(i+1 - last[j])

M = int(input())
for i in range(M):
    d, q = map(int, input().split())
    e = con[d-1] #i日目にやるコンテスト
    l1 = 0
    l2 = 0
    tmpe = 0
    tmpq = 0
    f1 = D
    f2 = D
    for j in range(D):
        if j < d-1:
            if con[j] == e:
                l1 = j #変更前のコンテストを直前の最後にいつやったか
            if con[j] == q:
                l2 = j #変更後のコンテストを直前の最後にいつやったか
        if j > d-1:
            if con[j] == e and tmpe == 0:
                f1 = j #変更前のコンテストを直後にいつやったか
                tmpe = 1
            if con[j] == q and tmpq == 0:
                f2 = j #変更後のコンテストを直後にいつやったか
                tmpq = 1
    con[d-1] = q
    ans = ans - S[d-1][e-1] + S[d-1][q-1] + C[q-1]*(f2-d+1)*(d-l2) - C[e-1]*(f1-d+1)*(d-l1)
    print(ans)

Submission status: Wrong Answer

Solution code:
d = int(input())
cl = list(map(int, input().split()))
sl = []
for _ in range(d):
    sl.append(list(map(int, input().split())))

tl = []
# for _ in range(d):
#     tl.append(int(input()))

last_di = [-1]*26
ans = 0
for day in range(d):
    # if day <= 100:
    #     coef = 1.0*day/36.0 + 3.0
    # else:
    #     coef = 10.0 - 1.0*day/36.0 + 3.0
    coef = 5.0 - day/400.0
    best_t = 0
    best_t_val = -999999999999
    for t in range(26):
        curr_val = sl[day][t]*1
        for i in range(26):
            if i == t: continue
            curr_val -= (day-last_di[i])*cl[i]*coef
        if curr_val >= best_t_val:
            best_t = t
            best_t_val = curr_val
    tl.append(best_t+1)
    last_di[best_t] = day
    ans += best_t_val
    # print(ans)
    # print('-- {}---'.format(day))
    # print(best_t)
    # print(last_di)

for t in tl:
    print(t)

# for day, t in enumerate(tl):
#     ans += sl[day][t-1]
#     last_di[t-1] = day
#     for ld, c in zip(last_di, cl):
#         # if ld == -1: continue
#         ans -= (day-ld)*c
#     print(ans)