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: Runtime Error

Solution code:
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 = [[] for _ in range(26)]
    satisfied = 0
    for d, t in enumerate(T):
        t -= 1; d += 1
        satisfied += Ss[d-1][t]
        used[t].append(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に変える

    # bi-1 -> bi -> bi+1 を bi-1 -> bi+1
    befind = Used[bef].index(d)
    befday0 = 0 if befind == 0 else Used[bef][befind-1]
    befday2 = Days+1 if befind == len(Used[bef])-1 else 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
        newaft = []
        for i,a in enumerate(Used[aft]):
            if a < d:
                aftday0 = a
            elif aftday2 == Days+1:
                newaft.append(d)
                aftday2 = a
            newaft.append(a)
        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:
        newaft = [d]
        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].remove(d)
    Used[aft] = newaft
    T[d-1] = aft+1
    Satisfied += deltaSatis
    print(Satisfied)

Submission status: Runtime Error

Solution code:
def calc_score(sch):
    d=[0]*26
    score=0
    for i in range(dur):
        j=sch[i]-1
        s=S[i]
        score+=s[j]+c[j]*(i+1-d[j])+sum([-c[k]*(i+1-d[k]) for k in range(26)])
        d[j]=i+1
    return score

def greedy(dur,c,S,r):
    sch=[]
    d=[0]*26
    for i in range(dur):
        t=0
        s=S[i]
        m=-1<<64
        for j in range(26):
            alt=s[j]+r*c[j]*(i+1-d[j])+sum([-r*c[k]*(i+1-d[k]) for k in range(26)])
            #alt=s[j]-(-c[j]*(i+1-d[j])+sum([c[k]*(i+1-d[k]) for k in range(26)]))**r
            if alt>m:
                m=alt
                t=j
        sch.append(t+1)
        d[t]=i+1
    return sch

dur=int(input())
c=list(map(int,input().split()))
S=[list(map(int,input().split())) for i in range(dur)]

T=50
a,b=1,8
R=1
tmp=-inf

for r in [a+i*(b-a)/T for i in range(T)]:
    alt_sch=greedy(dur,c,S,r)
    alt=calc_score(alt_sch)
    if tmp<alt:
        tmp=alt
        sch=alt_sch
        R=r

for i in sch:
    print(i)

Submission status: Runtime Error

Solution code:
import copy

D = int(input())
c = list(map(int,input().split()))
s = [list(map(int,input().split())) for i in range(D)]
t = [int(input()) for i in range(D)]
M = int(input())
d = [list(map(int,input().split())) for i in range(M)]
tmp = 0
last = [0]*(26)
last_list =[0]*D
tmp_list = [0]*(26)
day = 0
v = [0]*(D+1) #満足度これだけi=日付他のはi-1=日付
v_num = [0]*(D+1)
for day in range(D):
	for i in range(26):#今day+1日目
		tmp_list[i] = v[day]+ s[day][i]
		for j in range(26):
			if j != i:
				tmp_list[i] -= c[j] * (day+1 - last[j]) 
	v[day+1] = max(tmp_list)
	last[tmp_list.index(max(tmp_list))] = day + 1 
	last_list[day]=copy.deepcopy(last)
	v_num[day+1] = tmp_list.index(max(tmp_list)) +1
#print(last_list)

for k in range(M):
	tmp_v = copy.deepcopy(v)
	tmp_last_list = copy.deepcopy(last_list)
	tmp_v_num = copy.deepcopy(v_num)
	tmp_v_num[d[k][0]] = d[k][1] - 1
	day = d[k][0] - 1 #五日目なら4
	last = copy.deepcopy(tmp_last_list[day])
	for i in range(day,D):
		tmp_v[i + 1] = tmp_v[i]+ s[i][tmp_v_num[i+1]]
		for j in range(26):
			tmp_v[i+1] -= c[j] * (i+1 - last[j]) 

		last[tmp_v_num[i+1]-1] = i + 1 
		last_list[day]=copy.deepcopy(last)
	if tmp_v[D] > v[D]:
		v = copy.deepcopy(tmp_v)
		v_num = copy.deepcopy(tmp_v_num)
		last_list = copy.deepcopy(tmp_last_list)
for i in range(1,D+1):
	#print(v_num[i])
	print(v[i])

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np
d = int(input())
cs = list(map(int, input().split()))
sm = [list(map(int, input().split())) for _ in range(d)]

cs = np.array(cs, dtype=np.int64)
sm = np.array(sm, dtype=np.int64)

@njit('i8(i8[:])', cache=True)
def total_satisfaction(ts):
    ls = np.zeros(26, dtype=np.int64)
    s = 0
    for i in range(d):
        t = ts[i]
        t -= 1
        s += sm[i][t]
        ls[t] = i + 1

        dv = cs * ((i+1) - ls)
        s -= dv.sum()
    return s


@njit('void(i8[:],i8[:,:])', cache=True)
def fn(ts, dqs):
    for di, qi in dqs:
        ts[di - 1] = qi
        s = total_satisfaction(ts)
        print(s)

ts = [int(input()) for _ in range(d)]
m = int(input())
dqs = [list(map(int, input().split())) for _ in range(m)]

ts = np.array(ts, dtype=np.int64)
dqs = np.array(dqs, dtype=np.int64)
fn(ts, dqs)

Submission status: Runtime Error

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

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

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

INF = 10**9


def culc_value(t):
    last = [0] * 26
    value = 0
    for d in range(D):
        type = t[d]
        value += s[d][type - 1]
        last[type - 1] = d + 1
        for i in range(26):
            value -= c[i] * (d + 1 - last[i])
    return value


v_lastday = []
value = culc_value(t)

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

    # qに変換後のマイナス計算
    q_prev = 0
    q_next = 365
    for i in range(D):
        if t[i] == q and i + 1 != d:
            if q_prev < d:
                q_prev = i + 1
                continue
            elif d < q_next:
                q_next = i + 1
                break
    x = q_next - q_prev
    value += ((x + 1) * x // 2) * c[q - 1]
    y = d - q_prev
    z = q_next - d
    value -= (((y + 1) * y // 2) + (z + 1) * z // 2) * c[q - 1]

    # 変換前のt[d-1]のマイナス計算を直す
    r = t[d-1]
    r_prev = 0
    r_next = 365
    for i in range(D):
        if t[i] == r and i + 1 != d:
            if r_prev < d:
                r_prev = i + 1
                continue
            elif d < r_next:
                r_next = i + 1
                break
    x = r_next - r_prev
    value -= ((x + 1) * x // 2) * c[r - 1]
    y = d - r_prev
    z = r_next - d
    value += (((y + 1) * y // 2) + (z + 1) * z // 2) * c[r - 1]

    t[d - 1] = q
    v_lastday.append(value)

for x in v_lastday:
    print(x)


"""
for i in range(D):
    print(v[i])
"""

Submission status: Runtime Error

Solution code:
import sys
import math
import fractions
import time
import random
from collections import deque
from collections import defaultdict
sys.setrecursionlimit(10**7)

start = time.perf_counter()

D = int(input())
c = list(map(int, input().split()))
s = []
last = [0] * 26
for _ in range(D):
    line = list(map(int, input().split()))
    s.append(line)


def calc_one_score(t, d, sat):
    t -= 1
    sat += s[d][t]
    last[t] = d + 1
    for i in range(26):
        sat -= c[i] * (d + 1 - last[i])
    return sat


def calc_score(ts):
    sat = 0
    for d in range(D):
        sat = calc_one_score(ts[d], d, sat)
    return sat


max_score = 0

ts = [1, 17, 13, 14, 13]
while time.perf_counter() - start < 1.90:
    last = [0] * 26
    score = calc_score(ts)
    if max_score < score:
        max_score = score
        # print(ts, score)
    else:
        ts[d] = old
    d = random.randrange(D)
    i = random.randrange(1, 27)
    old = ts[d]
    ts[d] = i

for t in ts:
    print(t)
# print(max_score)

Submission status: Runtime Error

Solution code:
import copy

def main():


    d = int(input())
    cList = [int(x) for x in input().split()]

    sList = []

    for idx in range(0, d):
        tempList = [int(x) for x in input().split()]
        sList.append(tempList)

    tList = []

    for idx in range(0, d):
        tList.append(int(input()))

    m = int(input())
    qList = []

    for idx in range(0, m):
        tmpList = [int(x) for x in input().split()]
        qList.append(tmpList)

    val = calcVal(sList, tList, cList, d)

    for qidx in range(0, m):
        change_date = qList[qidx][0]

        temp_tlist = copy.deepcopy(tList)
        temp_tlist[change_date -1] = qList[qidx][1] #日付書き換え

        opp_val = val
        opp_val += sList[change_date -1][qList[qidx][1] -1]
        opp_val -= sList[change_date -1][tList[qList[qidx][0] -1]]

        counter = 0
        tmp_date = change_date -1+1
        while tmp_date < d and qList[qidx][1] != tList[tmp_date]:
            counter += 1
            tmp_date += 1
        opp_val += cList[qList[qidx][1] -1] * counter

        counter = 0
        tmp_date = change_date -1+1
        while tmp_date < d and tList[qList[qidx][0] -1] != tList[tmp_date]:
            counter += 1
            tmp_date += 1
        opp_val -= cList[tList[qList[qidx][0] -1]] * counter



        temp_tlist[qList[qidx][0] -1] = qList[qidx][1] #日付書き換え

        val = calcVal(sList, temp_tlist, cList, d)
        #if (opposit_val > val):
        #val = opposit_val
        tList = temp_tlist

        print(val)



def calcVal(sList, tList,cList, d):

    count_list = [0] * 26
    val = 0

    for idx in range(0, d):
        val += int(sList[idx][tList[idx] - 1])

        count_list = list(map(lambda x: x + 1, count_list))
        count_list[int(tList[idx]) - 1] = 0

        for wkChar in range(0, 26):
            val -= int(count_list[wkChar]) * int(cList[wkChar])

    return val


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from functools import lru_cache
import numpy as np

@lru_cache()
def calc_manzoku(D,c,s,t):
        manzoku = 0
        last_day = np.array([0]*26)
        day_pulse = np.array([1]*26)
        for day in range(1,D+1):
            contest_number = t[day-1] #開催するコンテスト種類
            manzoku += s[day-1,contest_number-1] #開催したコンテストによる満足度上昇
            last_day += day_pulse #経過日数の計算
            last_day[contest_number -1 ] = 0 #開催したコンテスト種類の経過日数を0に
            manzoku -= sum(c*last_day) #開催していないコンテストによる満足度の減少

        return manzoku
#基本入力
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()))
M = int(input())
dq = []
for i in range(M):
    dq.append(list(map(int,input().split())))
        
#基本入力完了
#得点計算
c = np.array(c)
s = np.array(s)
t = np.array(t)

manzoku = calc_manzoku(D,c,s,t)

#変えたものだけに着眼する。
for quri in range(M):
    t[dq[quri][0]-1] = dq[quri][1]
    manzoku = calc_manzoku(D,c,s,t)
    print(manzoku)

Submission status: Runtime Error

Solution code:
import numpy as np
from itertools import product

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

P2 = list(product(range(26), repeat=2))
P3 = list(product(range(26), repeat=3))

for d in range(0, D, 3):
    scores = []
    for t1, t2, t3 in P3:
        LL = L.copy()

        score = 0
        for dd in range(d, d+3):
            LL[t] = dd
            score += S[d, t] - np.dot(C, dd-LL)

        scores.append(score)

    smax = scores[0]
    tmax = 0
    for t, s in enumerate(scores):
        if s>smax:
            smax = s
            tmax = t

    for tt, dd in zip(P3[tmax], range(d, d+3)):
        L[tt] = dd
        print(tt+1)

d = 363
scores = []
for t1, t2 in P2:
    LL = L.copy()

    score = 0
    for dd in range(d, d+2):
        LL[t] = dd
        score += S[d, t] - np.dot(C, dd-LL)

    scores.append(score)

smax = scores[0]
tmax = 0
for t, s in enumerate(scores):
    if s>smax:
        smax = s
        tmax = t

for tt, dd in zip(P2[tmax], range(d, d+3)):
    L[tt] = dd
    print(tt+1)

Submission status: Runtime Error

Solution code:
import copy

def main():


    d = int(input())
    cList = [int(x) for x in input().split()]

    sList = []

    for idx in range(0, d):
        tempList = [int(x) for x in input().split()]
        sList.append(tempList)

    tList = []

    for idx in range(0, d):
        tList.append(int(input()))

    m = int(input())
    qList = []

    for idx in range(0, m):
        tmpList = [int(x) for x in input().split()]
        qList.append(tmpList)

    val = calcVal(sList, tList, cList, d)

    for qidx in range(0, m):
        change_date = qList[qidx][0]

        temp_tlist = copy.deepcopy(tList)
        temp_tlist[change_date -1] = qList[qidx][1] #日付書き換え

        opp_val = val
        opp_val += sList[change_date -1][qList[qidx][1]]
        opp_val -= sList[change_date -1][tList[qList[qidx][0] -1]]

        counter = 0
        tmp_date = change_date -1+1
        while tmp_date < d and qList[qidx][1] != tList[tmp_date]:
            counter += 1
            tmp_date += 1
        opp_val += cList[qList[qidx][1]] * counter

        counter = 0
        tmp_date = change_date -1+1
        while tmp_date < d and tList[qList[qidx][0] -1] != tList[tmp_date]:
            counter += 1
            tmp_date += 1
        opp_val -= cList[tList[qList[qidx][0] -1]] * counter



        temp_tlist[qList[qidx][0] -1] = qList[qidx][1] #日付書き換え

        val = calcVal(sList, temp_tlist, cList, d)
        #if (opposit_val > val):
        #val = opposit_val
        tList = temp_tlist

        print(val)



def calcVal(sList, tList,cList, d):

    count_list = [0] * 26
    val = 0

    for idx in range(0, d):
        val += int(sList[idx][tList[idx] - 1])

        count_list = list(map(lambda x: x + 1, count_list))
        count_list[int(tList[idx]) - 1] = 0

        for wkChar in range(0, 26):
            val -= int(count_list[wkChar]) * int(cList[wkChar])

    return val


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import itertools
            
def input():
    return sys.stdin.readline()[:-1]
  
def resolve():
    d = int(input())
    ci = list(map(int, input().split()))
    si = [list(map(int, input().split())) for _ in range(d)]
    answers = [int(input()) for _ in range(d)]

    #print(d, ci, si, answers)

    num_que = int(input())
    que = [list(map(int, input().split())) for _ in range(num_que)]
    #print(num_que, que)

    # queによる変更
    for q in range(num_que):
        answers[que[q][0]-1] = que[q][1]

        # 和の計算
        score_now = 0
        # コンテストごとの最後の実行日
        last_dates = [-1]*26
        for date in range(d):
            answer = answers[date]
            score_now += si[date][answer-1]

            last_dates[answer-1] = date
            c_date = map(lambda x:date-x, last_dates)
            score_now -= sum(map(mul, ci, c_date))
        # 最終スコア
        print(score_now)
resolve()

Submission status: Runtime Error

Solution code:
import random
import sys
input = sys.stdin.readline
d=int(input())
c=list(map(int,input().split()))
cn=sorted(c)
h=cn[3]
P=[k+1 for k,v in enumerate(c) if v>=h]
s=[]
for _ in range(d):
    s.append(list(map(int,input().split())))
# t=[]
# for _ in range(d):
#     t.append(int(input()))
# m=int(input())
t=[]
for _ in range(d):
    z=random.randrange(len(P))
    t.append(P[z])

m=1000
q=[]
for _ in range(m):
    z2=random.randrange(len(P))
    z1=random.randrange(d)
    q.append(tuple(z1,P[z2]))
p=-float("inf")
for k in range(m):
    ld=[-1]*26
    sc=0
    od=t[q[k][0]-1]
    t[q[k][0]-1]=q[k][1]

    for i in range(d):
        sc+=s[i][t[i]-1]
        ld[t[i]-1]=i

        C=0
        for j in range(26):
            C+=c[j]*(i-ld[j])
        sc-=C
    if p<sc:
        p=sc
    else:
        t[q[k][0]-1]=od

print(*t)

Submission status: Runtime Error

Solution code:

d=int(input())
c=input()
cl=[int(n) for n in c.split()]
sl=list()
for i in range(d):
    s=input()
    sl=sl+[int(n) for n in s.split()]
tl=list()
for i in range(d):
    t=int(input())
    tl.append(t)
sat=0
for i in range(d):
    sat+=sl[i*26+tl[i]-1]

def decr(tl,cl):
    dec=0
    for i in range(26):
        last=[a for a, x in enumerate(tl) if x==i+1]
        if last==list():
            dec+=(d*(d+1)/2)*cl[i]
        else:
            for v in range(len(last)):
                if v!=len(last)-1:    
                    dec+=cl[i]*(last[v+1]-last[v]-1)*(last[v+1]-last[v])/2
                else:
                    dec+=cl[i]*(d-last[v]-1)*(d-last[v])/2
            dec+=cl[i]*(last[0])*(last[0]+1)/2
    return(int(dec))

score=sat
m=int(input())
for k in range(d):
    q=input()
    q0=q.split()
    da=int(q0[0])
    q=int(q0[1])
    cha=sl[(da-1)*26+q-1]-sl[(da-1)*26+tl[da-1]-1]
    tl[da-1]=q
    score+=cha
    print(score-decr(tl,cl))

Submission status: Runtime Error

Solution code:
d = int(input())
c = list(map(int, input().split()))
score = []
for i in range(d):
    score.append(list(map(int, input().split())))
last_day = [0 for i in range(26)]
k = 0
for i in range(d):
    ans = 0
    max_score = -10**9
    for j in range(1, 27):
        s = score[i][j-1]
        for k in range(1,27):
            if j == k:
                continue
            else:
                s -= c[k-1] * (d - i+1 - last_day[k-1])
        if s > max_score:
            ans = j
            max_score = s
    last_day[ans] = i+1
    print(ans)
    k += max_score

Submission status: Runtime Error

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 *

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-=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[oq][idx2+1] - d
    if idx2 == len(last[q])-1:
        cntprv = D - last[oq][idx2] - cnt
    else:
        cntprv = last[oq][idx2+1] - last[oq][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: Runtime Error

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

    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[t].pop(i)
    X[q].insert(i, d)

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

    print(score)

Submission status: Runtime Error

Solution code:
l = [1, 2] 
print(l-1)

Submission status: Runtime Error

Solution code:
#create date: 2020-06-28 21:05

import sys
stdin = sys.stdin
import numpy as np
from numba import njit

def ns(): return stdin.readline().rstrip()
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))


def calc(t, s, c, d):
        period = np.zeros(26)
        last_day = np.zeros(26)
        v = 0
        for day in range(1, d+1):
            last_day[t[day-1]] = day
        
            v += s[day-1][t[day-1]]
            v -= (np.sum(c * (day - last_day)))
        return print(int(v))

def main():
    d = ni()
    c = np.array(na())
    s = list()
    for i in range(d):
        a = na()
        s.append(a)
    t = list()
    for i in range(d):
        t.append(ni()-1)

    
    m = ni()
    for i in range(m):
        di, qi = na()
        t[di-1] = qi-1
        calc(t, s, c, d)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

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)]
dic = {}
check = [[0 for j in range(26)] for i in range(D)]
con = []

ans = 0
for i in range(D):
    t = int(input())
    last[t-1] = i+1
    ans += S[i][t-1]
    check[i][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 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 rmpq == 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)