Problem:


Score : 400 points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

R points for winning with Rock;

S points for winning with Scissors;

P points for winning with Paper.

However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq N-1

1 \leq R,S,P \leq 10^4

N,K,R,S, and P are all integers.

|T| = N

T consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

N K
R S P
T

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996



Sample input:
5 2
8 7 6
rsrpr


Sample output:
27

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = list(input())

ans = 0
hands = []
for i in range(N):
    if i < K:
        # グー
        if T[i] == 'r':
            ans += P
            hands.append('p')
        # チョキ
        elif T[i] == 's':
            ans += R
            hands.append('r')
        # パー
        else:
            ans += S
            hands.append('s')
    else:
        if T[i] == 'r':
            if hands[i-K] != 'p':
                ans += P
                hands.append('p')
            else:
                if i + K <= N - 1:
                    hands.append('-')
                else:
                    hands.append('-')
        # チョキ
        elif T[i] == 's':
            if hands[i-K] != 'r':
                ans += R
                hands.append('r')
            else:
                if i + K <= N - 1:
                    hands.append('-')
                else:
                    hands.append('-')
        # パー
        else:
            if hands[i-K] != 's':
                ans += S
                hands.append('s')
            else:
                if i + K <= N - 1:
                    hands.append('-')
                else:
                    hands.append('-')

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()

dp = [[0]*3 for i in range(n+1)]
# dp[i][今回の手]

for i in range(n):
    if t[i] == "r":
        dp[i+1][0] = max(dp[max(i+1-k, 0)][1] + p, dp[i+1][0])
        dp[i+1][0] = max(dp[max(i+1-k, 0)][2] + p, dp[i+1][0])
    if t[i] == "s":
        dp[i+1][1] = max(dp[max(i+1-k, 0)][0] + r, dp[i+1][1])
        dp[i+1][1] = max(dp[max(i+1-k, 0)][2] + r, dp[i+1][1])
    if t[i] == "p":
        dp[i+1][2] = max(dp[max(i+1-k, 0)][0] + s, dp[i+1][2])
        dp[i+1][2] = max(dp[max(i+1-k, 0)][1] + s, dp[i+1][2])
    dp[i+1][0] = max(dp[max(i+1-k, 0)][1], dp[i+1][0])
    dp[i+1][0] = max(dp[max(i+1-k, 0)][2], dp[i+1][0])
    dp[i+1][1] = max(dp[max(i+1-k, 0)][0], dp[i+1][1])
    dp[i+1][1] = max(dp[max(i+1-k, 0)][2], dp[i+1][1])
    dp[i+1][2] = max(dp[max(i+1-k, 0)][0], dp[i+1][2])
    dp[i+1][2] = max(dp[max(i+1-k, 0)][1], dp[i+1][2])

ans = 0
for i in range(k):
    ans += max(dp[n-i])
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = list(map(int, input().split())) #グー・チョキ・パー
W=str(input())#rはグー・sはチョキ・pはパー
Q=list()
for i in range(len(W)):
    if i <K:
        if W[i]=='r':
            Q.append(P)
        elif W[i]=='s':
            Q.append(R)
        elif W[i]=='p':
            Q.append(S)
    else:
        if W[i]==W[i-K]:
            if Q[i-K]!=0:
                Q.append(0)
            else:
                if W[i]=='r':
                    Q.append(P)
                elif W[i]=='s':
                    Q.append(R)
                elif W[i]=='p':
                    Q.append(S)
        else:
            if W[i]=='r':
                Q.append(P)
            elif W[i]=='s':
                Q.append(R)
            elif W[i]=='p':
                Q.append(S)
print(sum(Q))

Submission status: Accepted

Solution code:
def d_prediction_and_restriction():
    from itertools import groupby
    N, K = [int(i) for i in input().split()]
    R, S, P = [int(i) for i in input().split()]
    T = input()

    ans = 0
    for i in range(K):
        tmp = groupby(T[i:N:K])
        for k, lst in tmp:
            v = len(list(lst))
            if v == 1:
                t = 1
            elif v % 2 == 0:
                t = v // 2
            else:
                t = v // 2 + 1
            if k == 'r':
                ans += P * t
            elif k == 's':
                ans += R * t
            elif k == 'p':
                ans += S * t
    return ans

print(d_prediction_and_restriction())

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n,k = inpl()
r = inpl()
t = input()
tt = [-1] * n
for i in range(n):
    if t[i] == 'r': tt[i] = 2
    elif t[i] == 's': tt[i] = 0
    else: tt[i] = 1
 
res = 0
for m in range(k):
    pre = -1
    for i in range(n)[m::k]:
        if tt[i] == pre:
            pre = -1
        else:
            res += r[tt[i]]
            pre = tt[i]
print(res)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())  # R=0, S=1, P=2
T = input()

_score = {'r': P, 's': R, 'p': S}
s = [P, R, S]
hand = {'r': 0, 's': 1, 'p': 2}
H = [' '] * N

dp = [[0] * 3 for _ in range(N + 1)]
for sub in range(1, K + 1):
    i = sub
    while i <= N:
        h = hand[T[i - 1]]
        for j in range(3):
            score = s[j] if j == h else 0
            dp[i][j] = max(dp[max(i - K, 0)][(j + 1) % 3], dp[max(i - K, 0)][(j + 2) % 3]) + score
        i += K

ans = 0
for k in range(K):
    ans += max(dp[N - k])

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
ans, win = 0, {'r': 'P', 's': 'R', 'p': 'S'}
for i in range(K):
    prev = '-'
    for t in T[i::K]:
        if not prev == win[t]:
            ans += eval(win[t])
            prev = win[t]
        else:
            prev = '-'
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int, input().split()) 
r,s,p=map(int, input().split()) 
T = str(input())
box = ["e" for i in range(len(T))]

for i in range(len(T)):
    if T[i] == "r":
        if box[i-k] != "p":
            box[i] = "p"
        else:
            box[i]="e"
    elif T[i]=="s":
        if box[i-k] != "r":
            box[i] = "r"
        else:
            box[i]="e"
    else:
        if box[i-k] != "s":
            box[i] = "s"
        else:
            box[i]="e"
for i in range(len(T)):
    if box[i] == "r":
        box[i]=r
    elif box[i]=="s":
        box[i]=s
    elif box[i]=="p":
        box[i]=p
    else:
        box[i]=0
print(sum(box))

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    r, s, p = map(int, input().split())
    t = list(input())

    score = 0
    for i in range(n):
        if i - k >= 0:
            if t[i] == t[i-k]:
                t[i] = "x"
                continue

        if t[i] == "r":
            score += p
        elif t[i] == "s":
            score += r
        elif t[i] == "p":
            score += s

    print(score)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
R,S,P=map(int,input().split())
T=list(input())

for i in range(N-K):
    if T[K+i]==T[i]:
        T[K+i]="x"
    #絶対に次の手を邪魔しない選択ができるので,ダブったら後の手を×にしときゃ良い
ans=T.count("r")*P+T.count("s")*R+T.count("p")*S

print(ans)

Submission status: Accepted

Solution code:
from itertools import groupby
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
d = {"r": P, "s": R, "p": S}
print(sum(sum(map(lambda p: d[p[0]]*((len(list(p[1]))+1)//2), groupby(T[k::K]))) for k in range(K)))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
r,s,p = map(int, input().split())
t=input()

def zyanken(x):
    if x=="r":
        return p
    elif x=="s":
        return r
    elif x=="p":
        return s

str_list = []
for i in range(k):
    str_list.append(t[i::k])

ans = 0

for g in str_list:
    dp = [0]*len(g)
    dp[0]=zyanken(g[0])
    before = g[0]
    for l in range(1,len(g)):
        if before!=g[l]:
            dp[l]=dp[l-1]+zyanken(g[l])
            before=g[l]
        else:
            dp[l]=dp[l-1]
            before="n"
    ans += dp[len(g)-1]
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
R, S, P = map(int, input().split())
t = input()

dp = [0] * n
dic = {'r': P, 's': R, 'p': S}

for i in range(n):
  if i >= k and (t[i-k] == t[i]) and dp[i-k] != 0:
    continue
  dp[i] = dic[t[i]]

print(sum(dp))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = list(input())

def func(i):
    if i == 'r':
        return 'p'
    elif i == 's':
        return 'r'
    else:
        return 's'

tp = [0] * n
for i in range(k):
    tp[i] = func(t[i])
for i in range(k, n):
    if tp[i - k] == func(t[i]):
        tp[i] = '-'
    else:
        tp[i] = func(t[i])
ans = (tp.count('r') * r) + (tp.count('p') * p) + (tp.count('s') * s)

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = list(input())
r, s, p = 0,0,0
for i in range(N):
	if i-K >= 0 and T[i-K] == T[i]:
		T[i] = None
	elif T[i] == 'r':
		p += 1
	elif T[i] == 's':
		r += 1
	elif T[i] == 'p':
		s += 1
print(r*R+s*S+p*P)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
r,s,p = map(int, input().split())
t = list(input())

ans = 0

i = 0

while i < n-k:
  if t[i] != t[i+k]:
    if t[i+k] == "r":
      ans += p
    elif t[i+k] == "s":
      ans += r
    else:
      ans += s
  else:
    if t[i+k] == "r":
      t[i+k] = "g"
    elif t[i+k] == "s":
      t[i+k] = "g"
    else:
      t[i+k] = "g"
  i += 1

for j in range(k):
  if t[j] == "r":
    ans += p
  elif t[j] == "s":
    ans += r
  else:
    ans += s 
      
print(ans)

Submission status: Accepted

Solution code:
def solve(r, s, p, t) -> int:
    R, S, P = 0, 1, 2

    n = len(t)
    dp = [[0] * 3 for _ in range(n + 1)]

    for i, c in enumerate(t, 1):
        dp[i][R] = max(dp[i - 1][S], dp[i - 1][P]) + (r if c == 's' else 0)
        dp[i][S] = max(dp[i - 1][P], dp[i - 1][R]) + (s if c == 'p' else 0)
        dp[i][P] = max(dp[i - 1][R], dp[i - 1][S]) + (p if c == 'r' else 0)

    return max(dp[n])


def main():
    n, k = map(int, input().split())
    r, s, p = map(int, input().split())
    t = input()

    ret = 0
    for i in range(k):
        ti = t[i::k]
        ret += solve(r, s, p, ti)

    print(ret)


if __name__ == '__main__':
    main()

# mod Kで小問題に分割して、
# 独立なk個の問題を解く

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
r,s,p = map(int,input().split())
t = input()
hand = ""
point = 0
for i in range(n):
    if i<k:
        if t[i] == "r":
            hand += "p"
        elif t[i] == "s":
            hand += "r"
        else:
            hand += "s"
    else:
        if t[i] == t[i-k] and hand[i-k] == "a":
            if t[i] == "r":
                hand += "p"
            elif t[i] == "s":
                hand += "r"
            else:
                hand += "s"
        elif t[i] == t[i-k] and hand[i-k] != "a":
            hand += "a"
        else:
            if t[i] == "r":
                hand += "p"
            elif t[i] == "s":
                hand += "r"
            else:
                hand += "s"

for i in range(n):
    if hand[i] == "p":
        point += p
    elif hand[i] == "r":
        point += r
    elif hand[i] == "s":
        point += s
    else:
        point += 0
print(point)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
R,S,P=map(int,input().split())
T=input()
count=0
for i in range(K):
    if i<N%K and N%K!=0:
        L=len(T)//K+1
    else:
        L=len(T)//K
    previous=""
    for j in range(L):
        if T[K*j+i]==previous:
            previous=""
        elif T[K*j+i]=="s":
            count+=R
            previous="s"
        elif T[K*j+i]=="r":
            count+=P
            previous="r"
        else:
            count+=S
            previous="p"
print(count)

Submission status: Accepted

Solution code:
n, k = [int(v) for v in input().split()]
r, s, p = [int(v) for v in input().split()]
t = input()


def get(seq, i):
    if i < 0:
        return None
    if i >= len(seq):
        return None
    return seq[i]

def get_win(c):
    if c == 'r':
        return 'p'
    elif c == 's':
        return 'r'
    else: # 'p'
        return 's'

def get_score(c):
    if c == 'r':
        return r 
    elif c == 's':
        return s
    else: # 'p':
        return p

score = 0
seq = [None] * n
for i in range(n):

    ti = t[i]
    win = get_win(ti)
    prev = get(seq, i-k)
    if win != prev:
        score += get_score(win)
        seq[i] = win
        continue

    n = get(t, i+k)
    if n is None:
        seq[i] = ti
    else:
        if prev is None:
            seq[i] = list(set('rsp') - set(n))[0]
        else:
            seq[i] = list(set('rsp') - set(n) - set(prev))
        
print(score)

Submission status: Accepted

Solution code:



N,K = map(int, input().split())
R,S,P = map(int, input().split())
T = input()



dp = [[0 for _ in range(3)] for _ in range(N+1)]

#マシン-高橋君の手の組で得られる点
plus = [[0,0,P],[R, 0,0],[0,S,0]]
mhand = {}
mhand["r"] = 0
mhand["s"] = 1
mhand["p"] = 2

order_p = [[] for _ in range(N+1)]

for i in range(N):
    for j in range(3):
        # まだK回やってないのでなんでも出せる
        if (i+1) <= K: 
            dp[i+1][j] = max(dp[i]) + plus[mhand[T[i]]][j]
        else:
            # 基本的には一回前の勝負の最大の部分から今の勝負に映るのが良い
            # 一方で、K回前と同じ手が出せないので、K回前と今回勝ちとなる手がおなじならその手は出せないので-INFとかでいいと思う
            # 例外的に、K回前の３個の得点のうち、最大得点がふたつあるなら、どちらからでも派生できるので、勝ちの手を出せる

            # 最大が二つなので、いずれにせよ最大から派生できる
            if order_p[i+1-K][-1][0] == order_p[i+1-K][-2][0]:
                dp[i+1][j] = max(dp[i]) + plus[mhand[T[i]]][j]
            # 今回勝てる手とK回目に出した手が被る場合、二番目に大きいところから派生
            else:
                if j == order_p[i+1-K][-1][1]:
                    dp[i+1][j] = -float("inf")
                else:
                    dp[i+1][j] = max(dp[i]) + plus[mhand[T[i]]][j]


    # K回前にどの手を出すと最大か分かるようにしておく
    order_p[i+1] = [(dp[i+1][0], 0), (dp[i+1][1], 1), (dp[i+1][2], 2)]
    order_p[i+1].sort()
            
             


print(max(dp[-1]))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
score_map = {
    "r": p,
    "p": s,
    "s": r,
    "n": 0,
}
t = list(t)
ans = 0
for i in range(k):
    skipped_list = t[i::k]
    for j, c in enumerate(skipped_list[1:]):
        if skipped_list[j] == c:
            skipped_list[j+1] = "n"
    for c in skipped_list:
        ans += score_map[c]
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
r,s,p = map(int,input().split())
st=input()
for i in range(len(st)-1):
    if i + k > len(st)-1:
        break
    elif st[i] == st[i+k]:
        st = st[:i+k]+'n'+st[i+k+1:]
win = r*st.count('s')+s*st.count('p')+p*st.count('r')
print(win)

Submission status: Accepted

Solution code:
n, k = map(int,input().split())
r, s, p = map(int, input().split())
t = input()
scoremap = {
    "r": p,
    "p": s,
    "s": r,
    "-": 0
}
t=[i for i in t]

def best(ls: list):
    for i in range(len(ls) - 1):
        if ls[i] == ls[i + 1]:
            ls[i + 1] = '-'
    num=sum([scoremap[i] for i in ls])
    return num

total=0
for i in range(k):
    ls = t[i::k]
    total+=best(ls)
print(total)

Submission status: Accepted

Solution code:
import numpy as np
N,K = map(int,input().split())
R,S,P = map(int,input().split())
Ts = np.array(list(str(input())))
T = np.zeros(N,dtype=int)

T[Ts=='r'] = P
T[Ts=='s'] = R
T[Ts=='p'] = S
for i in range(K, N):
    if Ts[i]==Ts[i-K] and T[i-K]!=0:
        T[i] = 0

print(np.sum(T))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()

from collections import Counter
winners_nums = sorted([R, S, P])
winners = Counter({R:'r', S: 's', P: 'p'})

min_winner = winners.get(winners_nums[0])
mapping = {'r': 'p', 's': 'r', 'p': 's'}

ans = 0
done = []
for t in T:
    win = mapping.get(t)
    if len(done) >= K:
        if done[len(done) - K] == win:
            hands = set(['r', 's', 'p']) - set([win])
            if len(T) > len(done) + K:
                not_next = mapping.get(T[len(done) + K])
                hands -= set([not_next])
            done.append(hands.pop())
            continue
    if win =='r':
        ans += R
    elif win == 's':
        ans += S
    else:
        ans += P
    done.append(win)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
R, S, P = map(int, input().split())
t = input()

dp = [0] * n
dic = {"r": P, "s": R, "p": S}


for i in range(n):
    if i >= k and (t[i - k] == t[i]) and dp[i - k] != 0:
        continue
    dp[i] = dic[t[i]]


print(sum(dp))

Submission status: Accepted

Solution code:
import sys
bbn=1000000007
	
#+++++
		
def main():
	n, k = map(int, input().split())
	r, s, p =  map(int, input().split())
	t = input()
	dd={'s':r, 'p':s, 'r':p}
	point = lambda c : dd[c]
	
	max_p=sum([point(c) for c in t])
	same_k={'s':0, 'p':0, 'r':0}
	tn=list(t)
	for i in range(k,n):
		if tn[i]==tn[i-k] and tn[i]!='_':
			same_k[tn[i]] += 1
			tn[i] = '_'
	down=0
	#print(tn)
	for cc in ['r','s','p']:
		down+=same_k[cc]*point(cc)
			
	print(max_p-down)
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()

hands = [None] * N
d1 = {'r': 'p', 's': 'r', 'p': 's'}
d2 = {'r': P, 's': R, 'p': S}
result = 0
for i in range(len(T)):
    if i >= K and d1[T[i]] == hands[i - K]:
        if i + K < N:
            hands[i] = list(set('rps') - set(d1[T[i]]) - set(d1[T[i + K]]))[0]
        else:
            hands[i] = T[i]
    else:
        hands[i] = d1[T[i]]
        result += d2[T[i]]
print(result)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=input()
score=0
te=[]
for a in range(n):
  if a-k>=0and te[0].count('prs'['rsp'.index(t[a])])==2:
    te+=[[t[a],'spr'['rsp'.index(t[a])]]]#;print(t[a],'あいこ')
  else:
    score+=[p,r,s]['rsp'.index(t[a])]#;print('prs'['rsp'.index(t[a])],'勝ち')
    te+=[['prs'['rsp'.index(t[a])]]*2]
  if a-k>=0:
    del te[0]
print(score)
#prrsp

Submission status: Accepted

Solution code:
from operator import add
from functools import reduce

N, K = list(map(int, input().split()))
R, S, P = list(map(int, input().split()))
T = list(input())
for i in range(N - K):
    s1 = T[i]
    s2 = T[i + K]
    if s1 == s2:
        T[i + K] = "0"
score = T.count("r") * P + T.count("s") * R + T.count("p") * S
print(score)

Submission status: Accepted

Solution code:
n, k = list(map(int, input().split()))
r,s,p = list(map(int, input().split()))
t = list(input())

win = {"r":p, "s":r, "p":s }
res = 0
for i in range(n-k):
  if(t[i+k] == t[i]):
    t[i+k] = 0
for i in range(n):
  if(t[i] != 0):
    res += win[t[i]]
print(res)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

n, k = map(int, readline().split())
r, s, p = map(int, readline().split())
t = read().rstrip().decode("utf-8")


points = {}
player = {}

player['r'] = 'p'
player['s'] = 'r'
player['p'] = 's'
points['p'] = p
points['r'] = r
points['s'] = s

ans = 0

for i in range(k):
    t_ = t[i::k] + '.'
    hands = ['.'] * len(t_)
    for i in range(len(t_) - 1):
        c = t_[i]
        if i < 1:
            ans += points[player[c]]
            hands[i] = player[c]
        elif player[c] != hands[i-1]:
            ans += points[player[c]]
            hands[i] = player[c]
        else:
            hands[i] = set(player.values()) and not player[c] and player[t_[i+1]]

print(ans)

Submission status: Accepted

Solution code:
def main():
    n, k = [int(i) for i in input().split()]
    r, s, p = [int(i) for i in input().split()]
    t = input()

    score = {
        "r": r,
        "s": s,
        "p": p,
        "x": 0
    }
    win_hand = {
        "r": "p",
        "s": "r",
        "p": "s"
    }
    my_hands = [win_hand[c] for c in t]
    for i in range(len(my_hands)):
        if i - k < 0:
            continue
        if my_hands[i] == my_hands[i - k]:
            my_hands[i] = "x"

    ans = 0
    for hand in my_hands:
        ans += score[hand]

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

n, k = map(int, readline().split())
r, s, p = map(int, readline().split())
t = read().rstrip().decode("utf-8")

hands = ['r', 's', 'p']

points = {}

player = {}
player['r'] = 'p'
player['s'] = 'r'
player['p'] = 's'
points['p'] = p
points['r'] = r
points['s'] = s

ans = 0

for i in range(k):
    t_ = t[i::k] + '.'
    myhand = ['.'] * len(t_)
    for i in range(len(t_) - 1):
        c = t_[i]
        if i < 1:
            ans += points[player[c]]
            myhand[i] = player[c]
        elif player[c] != myhand[i-1]:
            ans += points[player[c]]
            myhand[i] = player[c]
        else:
            myhand[i] = set(hands) and not player[c] and player[t_[i+1]]

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
r,s,p = map(int, input().split())
t=input()

def zyanken(x):
    if x=="r":
        return p
    elif x=="s":
        return r
    elif x=="p":
        return s

str_list = []
for i in range(k):
    str_list.append(t[i::k])

ans = 0

for g in str_list:
    hand = ""
    for l in range(len(g)):
        if l==0:
            hand+=g[0]
            ans+=zyanken(g[0])
        elif hand[l-1]==g[l]:
            hand+="n"
            ans+=0
        else:
            hand+=g[l]
            ans+=zyanken(g[l])

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()

ret = 0
for i in range(1, K+1):
    prev = '?'
    for j in range(len(T) // K + 1):
        if i + K*j - 1 >= len(T):
            continue
        now = T[i + K*j - 1]
        
        if prev == now:
            prev = '?'
        else:
            prev = now
            if now == 'r':  
                ret += P
            elif now == 's':
                ret += R
            else:
                ret += S
            
print(ret)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()

cnt = 0
memory = [None] * k

# r なら p　をだす、 s なら r　をだす, p なら s　をだす
for i in range(len(t)):
    if t[i] == 'r':
        if memory[i%k] != 'p':
            memory[i%k] = 'p'
            cnt += p
        elif i == len(t)-1: break
        else:
            if i+k < len(t):
                if t[i+k] == 's':
                    memory[i%k] = 's'
                else:
                    memory[i%k] = 'r'

    elif t[i] == 's':
        if memory[i%k] != 'r':
            memory[i%k] = 'r'
            cnt += r
        elif i == len(t)-1: break
        else:
            if i+k < len(t):
                if t[i+k] == 'p':
                    memory[i%k] = 'p'
                else:
                    memory[i%k] = 's'



    elif t[i] == 'p':
        if memory[i%k] != 's':
            memory[i%k] = 's'
            cnt += s
        elif i == len(t)-1: break
        else:
            if i+k < len(t):
                if t[i+k] == 'r':
                    memory[i%k] = 'r'
                else:
                    memory[i%k] = 'p'

print(cnt)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
ro, sc ,pa = map(int,input().split())
a = input()
dict = {'r':'p', 's':'r', 'p': 's'}
scores = {'r':ro,'s':sc,'p':pa}
can_lelect = 'rsp'
select = ['' for _ in range(n)]
cant = [[] for _ in range(n)]
left = 0
cur = k
for i in range(k):
    need = dict[a[i]]
    select[i] = need
while cur < n:
    need_cur = dict[a[cur]]
    need_left = dict[a[left]]
    if select[left] == '':
        select[left] = need_left
    if need_cur == select[left] :
        if select[left] != need_left:
            cant[left].append(need_cur)
            for v in can_lelect:
                if v not in cant[left]:
                    select[left] = v
                    break
            select[cur] = need_cur
        else:
            cant[cur].append(need_cur)
            for v in can_lelect:
                if  v not in cant[cur]:
                    select[cur] = v
                    break
    else:
        select[cur] = need_cur
    left+=1
    cur +=1
total = 0
for i in range(n):
    c = select[i]
    if c == dict[a[i]]:
        total+=scores[c]
print(total)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
point = 0

for i in range(k):
  part = t[i::k]
  R = part.count("r") - part.count("rr")
  S = part.count("s") - part.count("ss")
  P = part.count("p") - part.count("pp")
  point += R*p + S*r + P*s

print(point)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
ro, sc ,pa = map(int,input().split())
a = input()
dict = {'r':'p', 's':'r', 'p': 's'}
scores = {'r':ro,'s':sc,'p':pa}
can_lelect = 'rsp'
select = ['' for _ in range(n)]
cant = [[] for _ in range(n)]
left = 0
cur = k
for i in range(k):
    need = dict[a[i]]
    select[i] = need
while cur < n:
    need_cur = dict[a[cur]]
    need_left = dict[a[left]]
    if select[left] == '':
        select[left] = need_left
    if need_cur == select[left] :
        if select[left] != need_left:
            cant[left].append(need_cur)
            for v in can_lelect:
                if v not in cant[left]:
                    select[left] = v
                    break
            select[cur] = need_cur
        else:
            cant[cur].append(need_cur)
            right = cur+k
            if right < n:
                need_right = dict[a[right]]
                cant[cur].append(need_right)
            for v in can_lelect:
                if  v not in cant[cur]:
                    select[cur] = v
                    break
    else:
        select[cur] = need_cur
    left+=1
    cur +=1
total = 0
for i in range(n):
    c = select[i]
    if c == dict[a[i]]:
        total+=scores[c]
print(total)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import deque
import re
import math
import functools


def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29


def make1d_arr(n, val=INF):
    return [val for i in range(n)]


def make2d_arr(h, w, val=INF):
    return [[val for i in range(w)]for i in range(h)]


def gcd(a, b):
    if(b == 0):
        return a
    return gcd(b, a % b)


def BFord(n, es):
    v_cost = [INF]*n
    v_cost[0] = 0
    for v in range(n*2):
        for e in es:
            frm = e[0]
            to = e[1]
            if v_cost[to] > v_cost[frm]+e[2]:
                v_cost[to] = v_cost[frm]+e[2]
                if v >= n:
                    v_cost[to] = -INF
        if v == n-1:
            prev = v_cost[:]
    v_cost = [-INF if prev[idx] != v_cost[idx] else v_cost[idx]
              for idx in range(n)]
    return v_cost


def ZAlgo(s):
    l = len(s)
    A = [0]*l
    i = 1
    j = 0
    A[0] = l
    while i < l:
        while i+j < l and s[j] == s[i+j]:
            j += 1
        if j == 0:
            i += 1
            continue
        A[i] = j
        k = 1
        while (i+k < l) and (k+A[k] < j):
            A[i+k] = A[k]
            k += 1
        i += k
        j -= k
    return A


DIV = 998244353


def main():
    N,K = isRaw()
    R,S,P = isRaw()
    T = sRaw()
    Ts = [t for t in T]
    rsp = {"r":P,"s":R,"p":S}
    wPrise = [rsp[c] for c in T]
    ans=0
    for n in range(N):
        if n<K:
            ans += wPrise[n]
        elif Ts[n-K] != Ts[n]:
            ans += wPrise[n]
        else:
            Ts[n]="."
    return ans

    
if __name__ == "__main__":

    print(main())

Submission status: Accepted

Solution code:
N,K = list(map(int, input().split()))
R,S,P = list(map(int, input().split()))
T = list(map(str, input()))

res = 0

def change(hand):
    if hand == 'r':
        return 'p'

    if hand == 's':
        return 'r'

    if hand == 'p':
        return 's'

memo = []
for (i,t) in enumerate(T):
    if i > K-1:
        if memo[i-K] == change(t):
          memo.append(' ')
          continue
 
    if t == 'r':
        res = res+P
        memo.append(change(t))

    if t == 's':
        res = res+R
        memo.append(change(t))

    if t == 'p':
        res = res+S
        memo.append(change(t))

print(res)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
R,S,P=map(int,input().split())
T=list(input())

for j in range(N-K):
    if T[K+j] == T[j]:
        T[K+j] = 0
print(sum([T.count("r")*P, T.count("s")*R, T.count("p")*S]))