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:
# -*- coding: utf-8 -*-
from sys import stdin
from operator import itemgetter
from collections import deque, Counter
import math
import pprint
from functools import reduce
import numpy as np
# stdin = open("sample.txt")

MOD = 1000000007
INF = float('inf')
alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

def keta(kazu): # 入力されたintを桁ごとに分解，リストで出力
    kazu_str = str(kazu)
    kazu_list = [int(kazu_str[i]) for i in range(0, len(kazu_str))]
    return kazu_list

def gcd(*numbers): # 最小公倍数
    return reduce(math.gcd, numbers)

def combination(m,n): # mCn
    
    if n > m:
        return 'すまん'
    return math.factorial(m) // (math.factorial(m-n) * math.factorial(n))

def pow_k(x,n):  # (x**n)の計算の高速化
    if n == 0:
        return 1
    K = 1
    while n > 1:
        if n % 2 != 0:
            K *= x
        x *= x
        n //= 2
    return K * x

def fact(n): # nの素因数分解の結果を辞書で出力 fuct(24) → {2: 3, 3: 1}
    arr = {}
    temp = n
    for i in range(2,int(n**0.5)+1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr[i] = cnt
    if temp != 1:
        arr[temp] = 1
    if arr == {}:
        arr[n] = 1
    return arr

def main():
    d = int(stdin.readline().rstrip())
    c = list(map(int,[int(x) for x in stdin.readline().rstrip().split()]))
    table = [] # 得られる満足度
    last = [0]*26 # 最後に開催された日
    scoretable = []
    go = [] # 日付と開催されたコンテストの種類
    score = 0
    for _ in range(d):
        table.append(list(map(int,[int(x) for x in stdin.readline().rstrip().split()])))
    for D in range(d):
        go.append(int(stdin.readline().rstrip()) - 1)
        for i in range(26):
            if i == go[D]:
                score += table[D][i]
                last[i] = D+1
            else:
                score -= c[i]*(D+1-last[i])
        scoretable.append(score)
    Q = int(stdin.readline().rstrip())
    score = scoretable[-1]
    for i in range(Q):
        day, new = [int(x)-1 for x in stdin.readline().rstrip().split()]
        old = go[day]
        score = score - table[day][old] + table[day][new]
        if old in go[day+1:]:
            days = go[day+1:].index(old) + 1
            score -= days * c[old]
            print("in",days)
        else:
            days = len(go[day:])
            score -= days * c[old]
            print("not",days)
        go[day] = new
        if new in go[day+1:]:
            days = go[day+1:].index(new) + 1
            score += days * c[new]
            print("in",days)
        else:
            days = len(go[day:])
            score += days * c[new]
            print("not",days)
        print(score)
main()

Submission status: Wrong Answer

Solution code:
from time import time
start=time()
from copy import deepcopy
from random import randint

d=int(input())
c=list(map(int,input().split())) #scoreを減らす
s=[] #scoreを増やす
for i in range(d):
    t=list(map(int,input().split()))
    s.append(t)
last=[0]*26 #それぞれのコンテストが最後に行われたのは何日目か
ans_lst=[]

for i in range(1,d): #364日、1日目ならi=1
    temp_best=-100000000
    for j in range(26): #それぞれの日において、26個のコンテストを順番にピックアップ
        temp=s[i-1][j]
        for k in range(26): #ピックアップされていないコンテストは、スコアを減らす
            if j!=k:
                temp-=(c[k]*(i-last[k]))
        temp_last=deepcopy(last)
        temp_last[j]=i
        for k in range(26):
            temp+=s[i][k]
            for l in range(26):
                if k!=l:
                    temp-=(c[l]*(i+1-temp_last[l]))
        if temp>temp_best:
            temp_best=temp
            rem=j
    ans_lst.append(rem)
    last[rem]=i
    
temp_best=-100000000 #365日目は、次の日のことは考えなくてよい
for j in range(26): #26個のコンテストを順番にピックアップ
    temp=s[i-1][j]
    for k in range(26): #ピックアップされていないコンテストは、スコアを減らす
        if j!=k:
            temp-=(c[k]*(i-last[k]))
    if temp>temp_best:
        temp_best=temp
        rem=j
ans_lst.append(rem) #AtCoder運営お疲れ様です

score=0
las=[0]*26
for i in range(d):
    for j in range(26):
        las[j]+=1
    score+=s[i][ans_lst[i]]
    las[ans_lst[i]]=0
    for j in range(26):
        score-=c[j]*las[j]

for q in range(1,25):
    for p in range(d-q):
        las=[0]*26
        temp_score=0
        temp_ans_lst=deepcopy(ans_lst)
        temp_ans_lst[p],temp_ans_lst[p+q]=temp_ans_lst[p+q],temp_ans_lst[p]
        for i in range(d):
            for j in range(26):
                las[j]+=1
            temp_score+=s[i][temp_ans_lst[i]]
            las[temp_ans_lst[i]]=0
            for j in range(26):
                temp_score-=c[j]*las[j]
        if temp_score>score:
            score=temp_score
            ans_lst=temp_ans_lst

while time()-start<1.9:
    las=[0]*26
    temp_score=0
    temp_ans_lst=deepcopy(ans_lst)
    a=randint(0,d-2)
    b=randint(0,d-2)
    temp_ans_lst[a],temp_ans_lst[a+1]=temp_ans_lst[a+1],temp_ans_lst[a]
    temp_ans_lst[b],temp_ans_lst[b+1]=temp_ans_lst[b+1],temp_ans_lst[b]
    for i in range(d):
        for j in range(26):
            las[j]+=1
        temp_score+=s[i][temp_ans_lst[i]]
        las[temp_ans_lst[i]]=0
        for j in range(26):
            temp_score-=c[j]*las[j]
    if temp_score>score:
        score=temp_score
        ans_lst=temp_ans_lst

for i in ans_lst:
    print(i+1)

Submission status: Wrong Answer

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 i in range(D):
	v_num[i+1] = t[i]

ans = [0]*M
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]
	day = d[k][0] - 1 #五日目なら4

	if day!=0:
		last = copy.deepcopy(tmp_last_list[day-1])
	else:
		last =[0]*26

	for i in range(day,D):
		last[tmp_v_num[i+1]-1] = i + 1 
		tmp_v[i + 1] = tmp_v[i]+ s[i][tmp_v_num[i+1]-1]
		for j in range(26):

			tmp_v[i+1] -= c[j] * (i+1 - last[j]) 
	
		tmp_last_list[i]=copy.deepcopy(last)

	if 1==1:
		v = copy.deepcopy(tmp_v)
		v_num = copy.deepcopy(tmp_v_num)
		last_list = copy.deepcopy(tmp_last_list)
	#print(v_num)
	ans[k] = v[D]
"""
for i in range(1,D+1):
	#print(v_num[i])
	print(v[i])
"""
for i in range(M):
	#print(v_num[i])
	print(ans[i])

Submission status: Wrong Answer

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 i in range(D):
	v_num[i+1] = t[i]


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]
	day = d[k][0] - 1 #五日目なら4

	if day!=0:
		last = copy.deepcopy(tmp_last_list[day-1])
	else:
		last =[0]*26

	for i in range(day,D):
		last[tmp_v_num[i+1]-1] = i + 1 
		tmp_v[i + 1] = tmp_v[i]+ s[i][tmp_v_num[i+1]-1]
		for j in range(26):

			tmp_v[i+1] -= c[j] * (i+1 - last[j]) 
	
		tmp_last_list[i]=copy.deepcopy(last)

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

Submission status: Wrong Answer

Solution code:


import time
st = time.time()

d = int(input())
clist = list(map(int,input().split()))
last_c = [0]*26
select_c = [0]*26
for i in range(26):
    select_c[i] = []

slist = [0] * d
for i in range(d):
    slist[i] = list(map(int,input().split()))

tlist = [0]*d
satisfy = [0]*(d+1)

#貪欲法
for i in range(0,d):
    max = 0
    max_n = 0
    for n in range(26):
        if i > 0:
            curr = slist[i][n] + satisfy[i-1]
        else:
            curr = slist[i][n]
        minus = 0
        for j in range(26):
            if n != j:
                minus -= clist[j] * (i - last_c[j])
        curr += minus
        if curr > max:
            max = curr
            max_n = n
    satisfy[i] = max
    last_c[max_n] = i+1 
    select_c[max_n].append(i+1)
    tlist[i] = max_n+1

import random
import numpy as np

sum = 0
total_c = 0


for i in range(d):
    sum += slist[i][tlist[i]-1]

ct = time.time()

for i in range(len(select_c)):
    start = 1
    c_change = 0
    if select_c[i] == []:
        c_change = np.sum(np.arange(d+1))
    else:
        for j in range(len(select_c[i])):
            end = select_c[i][j]
            if end > start:
                c_change += np.sum(np.arange(end-start+1))
            start = end
        end = d+1
        c_change += np.sum(np.arange(end-start))
        start = end
    total_c += clist[i]*c_change

current_max = sum - total_c

try:

    import bisect
    while ct-st < 1.9:
        change_d = random.randint(1,d)
        change_d_to_c = random.randint(0,len(select_c)-1)
        for x in range(len(select_c)):
            try:
                ind = select_c[x].index(change_d)
                change = x
                s_change = slist[change_d-1][ind]
                select_c[x].remove(change_d)
                break
            except:
                None

        s_change2 = slist[change_d-1][change_d_to_c]

        bisect.insort(select_c[change_d_to_c],change_d)
        #calc
        sum2 = sum - s_change + s_change2
        total_c2 = 0
        for i in range(len(select_c)):
            start = 1
            c_change = 0
            if select_c[i] == []:
                c_change = np.sum(np.arange(d+1))
            else:
                for j in range(len(select_c[i])):
                    end = select_c[i][j]
                    if end > start:
                        c_change += np.sum(np.arange(end-start+1))
                    start = end
                end = d+1
                c_change += np.sum(np.arange(end-start))
                start = end
            total_c2 += clist[i]*c_change

        percent = random.random()
        if percent > 0.15 and sum - total_c < sum2 - total_c2:
            sum = sum2
            total_c = total_c2
            tlist[change_d-1] = change_d_to_c+1
        else:
            bisect.insort(select_c[change],change_d)
            select_c[change_d_to_c].remove(change_d)

        

        ct = time.time()
except:
    None
#remove first
for i in tlist:
    print(i)

Submission status: Wrong Answer

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

def g(a,d,T):
    try:
        return T[:d].index(a)
    except ValueError:
        return 0

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()))
            
X=0
L=[0]*(A+1)
R=[[0]*(A+1) for _ in range(D+1)]
for d in range(1,D+1):
    X+=S[d][T[d]]
    for j in range(1,A+1):
        if j!=T[d]:
            L[j]+=1
            R[d][j]=R[d-1][j]+1
            X-=C[j]*L[j]
        else:
            L[j]=0

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

    Y=(d-g(p,d,T))*(f(p,d,T)-d)
    Z=R[d][q]*(f(q,d,T)-d)
    
    h=R[d-1][p]
    for i in range(d,f(p,d,T)):
        h+=1
        R[i][p]=h

    m=0
    for j in range(d,f(q,d,T)):
        R[j][q]=m
        m+=1
    
    T[d]=q
    X+=(S[d][q]-S[d][p])+Z*C[q]-Y*C[p]
    print(X)

Submission status: Wrong Answer

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

def g(a,d,T):
    try:
        return T[:d].index(a)
    except ValueError:
        return 0

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()))
            
X=0
L=[0]*(A+1)
for d in range(1,D+1):
    X+=S[d][T[d]]
    for j in range(1,A+1):
        if j!=T[d]:
            L[j]+=1
            X-=C[j]*L[j]
        else:
            L[j]=0

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

    Y=(d-g(p,d,T))*(f(p,d,T)-d)
    Z=(d-g(q,d,T))*(f(q,d,T)-d)

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

Submission status: Wrong Answer

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

def g(a,d,T):
    try:
        return T[:d].index(a)
    except ValueError:
        return 0

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()))
            
X=0
L=[0]*(A+1)
for d in range(1,D+1):
    X+=S[d][T[d]]
    for j in range(1,A+1):
        if j!=T[d]:
            L[j]+=1
            X-=C[j]*L[j]
        else:
            L[j]=0

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

    Y=(d-g(p,d,T))*(f(p,d+1,T)-d)
    Z=(d-g(q,d,T))*(f(q,d+1,T)-d)

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

Submission status: Wrong Answer

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

def g(a,d,T):
    try:
        return T[:d].index(a)
    except ValueError:
        return 0

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()))
            
X=0
L=[0]*(A+1)
for d in range(1,D+1):
    X+=S[d][T[d]]
    for j in range(1,A+1):
        if j!=T[d]:
            L[j]+=1
            X-=C[j]*L[j]
        else:
            L[j]=0

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

    Y=(f(p,d+1,T)-d)*(d-g(p,d,T))
    Z=(f(q,d+1,T)-d)*(d-g(q,d,T))

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

Submission status: Wrong Answer

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

def g(a,d,T):
    try:
        return T[:d].index(a)
    except ValueError:
        return 0

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()))
            
X=0
L=[0]*(A+1)
for d in range(1,D+1):
    X+=S[d][T[d]]
    for j in range(1,A+1):
        if j!=T[d]:
            L[j]+=1
            X-=C[j]*L[j]
        else:
            L[j]=0

M=int(input())
for _ in range(M):
    d,q=map(int,input().split())
    p=T[d]
    
    Y=(f(p,d+1,T)-d)*(d-g(p,d,T))
    Z=(f(q,d+1,T)-d)*(d-g(p,d,T))

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

    T[d]=q

Submission status: Wrong Answer

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

def g(a,d,T):
    try:
        return T[:d].index(a)
    except ValueError:
        return 0

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()))
            
X=0
L=[0]*(A+1)
for d in range(1,D+1):
    X+=S[d][T[d]]
    for j in range(1,A+1):
        if j!=T[d]:
            L[j]+=1
            X-=C[j]*L[j]
        else:
            L[j]=0

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

    Y=(f(p,d+1,T)-d)*(d-g(p,d,T))
    Z=(f(q,d+1,T)-d)*(d-g(p,d,T))

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

Submission status: Wrong Answer

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] - 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 ans in v_lastday:
    print(ans)


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

Submission status: Wrong Answer

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

def g(a,d,T):
    try:
        return T[:d].index(a)
    except ValueError:
        return 0

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()))
            
X=0
L=[0]*(A+1)
for d in range(1,D+1):
    X+=S[d][T[d]]
    for j in range(1,A+1):
        if j!=T[d]:
            L[j]+=1
            X-=C[j]*L[j]
        else:
            L[j]=0

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

    Y=(f(p,d+1,T)-d)*(d-g(p,d,T))
    Z=(f(q,d+1,T)-d)*(d-g(p,d,T))

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

Submission status: Wrong Answer

Solution code:
D = int(input())
C = list(map(int, input().split()))
S = [list(map(int, input().split())) for _ in range(D)]
from bisect import *
scores = []
last = [-1]*26
score = 0
points = [0]*26
dates = [[-1] for _ in range(26)]
T = [int(input())-1 for _ in range(D)]
for d in range(D):
    dates[T[d]].append(d)
    score += S[d][T[d]]
    last[T[d]] = d
    for j in range(26):
        score -= C[j]*(d-last[j])
for i in range(26):
  dates[i].append(D)
M = int(input())
for _ in range(M):
  d,after = map(int, input().split())
  d -= 1
  after -= 1
  before = T[d]
  T[d] = after
  score += S[d][after]-S[d][before]
  ind_bef = bisect_right(dates[before],d)-1
  score -= C[before]*(d-dates[before][ind_bef-1])*(dates[before][ind_bef+1]-d)
  ind_aft = bisect_right(dates[after],d)-1
  score += C[after]*(d-dates[after][ind_aft-1])*(dates[after][ind_aft]-d)
  insort_right(dates[after],d)
  dates[before].pop(ind_bef)
  scores.append(score)
print(*scores, sep='\n')

Submission status: Wrong Answer

Solution code:
def main():
    d=int(input())
    c=list(map(int,input().split()))
    s=[list(map(int,input().split())) for _ in range(d)]
    last=[[0]*27 for _ in range(366)]
    srate=[0]
    T=[0]
    a=0
    for i in range(1,d+1):
        for j in range(27):
            last[i][j]=last[i-1][j]
        t=int(input())
        T.append(t)
        last[i][t]=i
        a+=s[i-1][t-1]
        for j in range(1,27):
            a-=c[j-1]*(i-last[i][j])
        srate.append(a)
    m=int(input())
    for i in range(m):
        D,Q=map(int,input().split())
        bt=T[D]
        pa=0
        for j in range(D,d+1):
            if T[j]!=Q:
                pa+=c[Q-1]*(j-last[j][Q])
                last[j][Q]=D
                pa-=c[Q-1]*(j-last[j][Q])
            if T[j]!=bt or j==D:
                pa+=c[bt-1]*(j-D)
                last[j][bt]=last[j-1][bt]
                pa-=c[bt-1]*(j-last[j][bt])
            if j==D:
                pa+=s[j-1][Q-1]-s[j-1][bt-1]
                T[j]=Q
            srate[j]+=pa
        print(srate[-1])

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

N_TYPE = 26


class SegmentTree:
    def __init__(self, size, f=lambda x, y: x+y, default=0):
        self.size = 2**(size-1).bit_length()
        self.default = default
        self.dat = [default]*(self.size*2)
        self.f = f

    def update(self, i, x):
        i += self.size
        self.dat[i] = x
        while i > 0:
            i >>= 1
            self.dat[i] = self.f(self.dat[i*2], self.dat[i*2+1])

    def query(self, l, r):
        l += self.size
        r += self.size
        lres, rres = self.default, self.default
        while l < r:
            if l & 1:
                lres = self.f(lres, self.dat[l])
                l += 1

            if r & 1:
                r -= 1
                rres = self.f(self.dat[r], rres)
            l >>= 1
            r >>= 1
        res = self.f(lres, rres)
        return res


class Contest:
    def __init__(self, date, t):
        self.prev = None
        self.next = None
        self.date = date
        self.type = t


def solve(d, c, s):
    best = [0] * d
    last = [-1]*N_TYPE

    for i in range(d):
        max_v = -float('inf')
        for j in range(N_TYPE):
            v = s[i][j] + c[j] * (i - last[j])
            if max_v < v:
                max_v = v
                best[i] = j
        last[best[i]] = i
    return best


def get_score(d, c, s, t):
    last = [-1]*N_TYPE
    total = 0
    for i in range(d):
        total += s[i][t[i]]
        last[t[i]] = i
        for j in range(N_TYPE):
            total -= c[j] * (i - last[j])
    return max(total, 0)


def get_pen(d1, d2):
    return (d2-d1)*(d2-d1+1)//2


def main():
    D = int(input())
    C = list(map(int, input().split()))
    S = [list(map(int, input().split())) for i in range(D)]
    T = [int(input())-1 for i in range(D)]
    score = get_score(D, C, S, T)

    nxt = [SegmentTree(D, min, default=D) for i in range(N_TYPE)]
    lst = [SegmentTree(D, max, default=-1) for i in range(N_TYPE)]

    for i in range(D):
        nxt[T[i]].update(i, i)
        lst[T[i]].update(i, i)
    m = int(input())
    for i in range(m):
        d, q = map(int, input().split())
        d -= 1
        q -= 1

        old = T[d]
        T[d] = q

        old_next = nxt[old].query(d + 1, D)
        old_last = lst[old].query(0, d)

        diff = S[d][q] - S[d][old]
        diff += -C[old] * get_pen(old_last, old_next)
        diff += +C[old] * get_pen(d, old_next)
        diff += +C[old] * get_pen(old_last, d)

        q_next = nxt[q].query(d + 1, D)
        q_last = lst[q].query(0, d)
        diff += +C[q] * get_pen(q_last, q_next)
        diff += -C[q] * get_pen(d, q_next)
        diff += -C[q] * get_pen(q_last, d)

        nxt[old].update(d, D)
        lst[old].update(d, -1)
        nxt[q].update(d, d)
        lst[q].update(d, d)

        score += diff
        print(score)


if __name__ == "__main__":
    main()