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

Solution (Python):
N, K = [int(i) for i in input().split()]
R, S, P = [int(i) for i in input().split()]
T=list(input())
score=[[0,0,0]*K]
for i in range(N-K):
    if T[i]==T[i+K]:
        T[i+K]="."

print(T.count("p")*S + T.count("s")*R + T.count("r")*P )

Solution (Python):

n,k = map(int,input().split())
d = dict()
d['s'],d['p'],d['r'] = map(int,input().split())
T = list(input())
ans = 0
for i in range(len(T)):
    if (i-k >= 0 and T[i-k]==T[i]):
        T[i] = "*"
    else:
        ans += d[T[i]]

print (ans)

Solution (Python):
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
li = list(t[:k])
cnt = 0
for itr, val in enumerate(t):
  if itr >= k and val == li[itr % k]:
    li[itr % k] = "x"
  else:
    if val == "r":
      cnt += p
    elif val == "s":
      cnt += r
    else:
      cnt += s
    li[itr % k] = val
print(cnt)

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

pt = {
  "r": P,
  "s": R,
  "p": S
}

ans = 0
l = [False] * N

for i in range(K):
  ans += pt[T[i]]
  l[i] = True

for i in range(K, N):
  if T[i] == T[i-K] and l[i-K]: continue
  ans += pt[T[i]]
  l[i] = True
    
print(ans)

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

def point(A):
    if A == "r":
        return P
    elif A == "s":
        return R
    else:
        return S

ans = 0
for i in range(K):
    s = T[i::K]
    t = "a"
    for j in range(len(s)):
        if t == s[j]:
            t = "a"
        else:
            ans += point(s[j])
            t = s[j]

print(ans)

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
def getscore(c):
  if c == "r":
    return P
  if c == "s":
    return R
  if c == "p":
    return S
  return 0
r = 0
for n in range(K):
  p = ""
  for i in range(n, N, K):
    c = T[i]
    if c == p:
      p = ""
    else:
      r += getscore(c)
      p = c
print(r)

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

win = {
    'r': p,
    's': r,
    'p': s
}
use = [False for i in range(len(t))]
score = 0
for i in range(len(t)):
    if i < k:
        score += win[t[i]]
        use[i] = True
    elif t[i] != t[i-k] or (not use[i-k]):
        score += win[t[i]]
        use[i] = True
print(score)

Solution (Python):
N, K = map(int,input().split())
R, S, P = map(int,input().split())
T = list(input())
d = {"r":P,"s":R,"p":S}
ans = 0
for i, v in enumerate(T):
    if i < K:
        ans += d[v]
    else:
        if v != T[i-K]:
            ans += d[v[0]]
        else:
            T[i] = v + "a"

print(ans)

Solution (Python):
n,k = map(int,input().split())
r,s,p = map(int,input().split())
t=input()
score=0
cnt=0
dame=""
for i in range(n):
    if k>i or dame[i-k]!=t[i]:
        if t[i]=='r':
            score+=p
            dame+='r'
        elif t[i]=='s':
            score+=r
            dame+='s'
        elif t[i]=='p':
            score+=s
            dame+='p'
    else:
        dame+='n'
print(score)

Solution (Python):


n, k = map(int, input().split(' '))
r, s, p = map(int, input().split(' '))
t = input()

str_arr = []
for i in range(k):
    j = i
    chars = ''
    while j < n:
        chars += t[j]
        j += k
    str_arr.append(chars)

total = 0
for chars in str_arr:
    pre_char = ''
    for char in chars:
        if pre_char == char:
            pre_char = ''
            continue
        else:
            if char == 'r':
                total += p
            elif char == 'p':
                total += s
            else:
                total += r
        pre_char = char
print(total)

Solution (Python):

import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


N, K = read_ints()
R, S, P = read_ints()
T = read()[:-1]

points = {
    'r': P,
    's': R,
    'p': S
}







handsls = []

ans = 0
for i in range(N):
    now = T[i]
    if i < K:
        ans += points[now]
        handsls.append(now)
    else:
        if now == handsls[i - K]:
            handsls.append('n')
            continue
        ans += points[now]
        handsls.append(now)
        

print(ans)

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

t=input()
ans=0
janken={"r":p,"s":r,"p":s}
aiko=[]
for i in range(n):
    if i<k:
        ans+=janken[t[i]]
        aiko.append(False)
    else:
        
        if t[i-k]!=t[i] or (t[i-k]==t[i] and aiko[i-k]):
            ans+=janken[t[i]]
            aiko.append(False)
        else:
            aiko.append(True)
    
print(ans)

Solution (Python):
n,k = map(int,input().split())
r,s,p = map(int,input().split())
t = list(input())
point = 0
result = []
for i in range(n):
  if i+1 <= k or result[i-k] == "f" or t[i] != t[i-k]:
    if t[i] == "r":
      point += p
    elif t[i] == "s":
      point += r
    else:
      point += s
    result.append("t")
  else:
    result.append("f")
print(point)

Solution (Python):
d = {'r': 0, 's': 1, 'p': 2}
win = {0: 2, 1: 0, 2: 1}

N, K = map(int, input().split())
point = list(map(int, input().split()))
T = input()

dp = [[0]*3 for _ in range(K)]  

for i in range(N):
    k = i%K
    w = win[d[T[i]]]
    mx, mxw = 0, 0
    for j in range(3):
        mx = max(mx, dp[k][j])
        if j != w:
            mxw = max(mxw, dp[k][j])
    for j in range(3):
        if j != w:
            dp[k][j] = mx   
        else:
            dp[k][j] = mxw + point[j]   

ans = 0
for i in range(K):
    mx = 0
    for j in range(3):
        mx = max(mx, dp[i][j])
    ans += mx


print(ans)

Solution (Python):

N, K = map(int,input().split())
R, S, P = map(int,input().split())
T = [str(x) for x in input()]
ans = 0


for k in range(K):
    if T[k] == "r":
        ans += P
    elif T[k] == "p":
        ans += S
    else:
        ans += R

for k in range(K,N):
    if T[k] == "r":
        if T[k-K] != "r":
            ans += P
        else:
            T[k] = "_"
    elif T[k] == "p":
        if T[k-K] != "p":
            ans += S
        else:
            T[k] = "_"
    else:
        if T[k-K] != "s":
            ans += R
        else:
            T[k] = "_"


print(ans)

Solution (Python):
n,k = map(lambda x: int(x),input().split())
r,s,p = map(lambda x: int(x),input().split())
t = input()
ans = ''
dont = 'free'
count = 0
for i in range(n):
    if i - k >= 0 :
        dont = ans[i-k]
    if t[i] == 'r' and dont != 'p':
        ans += 'p'
        count += p
    elif t[i] == 's' and dont != 'r' :
        ans += 'r'
        count += r
    elif t[i] == 'p' and dont != 's':
        ans += 's'
        count += s
    else :
        ans += 'f'
print(count)

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


def f(ch):
    if ch == 'r':
        return 'p'
    elif ch == 's':
        return 'r'
    else:
        return 's'

te = []
for i in range(N):
    r = f(T[i])
    if i < K:
        te.append(r)
    else:
        if te[i-K] == r:
            te.append('*')
        else:
            te.append(r)

ans = 0
for ti in te:
    if ti == 'r':
        ans += R
    elif ti == 's':
        ans += S
    elif ti == 'p':
        ans += P
print(ans)

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = list(input())
j = 0
U = []
for i in T:
    if j < K:
        U.append(i)
    else:
        if U[j-K] == "o":
            U.append(i)
        elif T[j-K] == i:
            U.append("o")
        else:
            U.append(i)
    j += 1
print(U.count("r")*P+U.count("s")*R+U.count("p")*S)

Solution (Python):
N , K = map(int,input().split())
R , S , P = map(int,input().split())
T = list(input())
is_get_list = [True] * K
ans = 0


for i in range(K , N):
    now = T[i]
    before = T[i - K]
    if now == before and is_get_list[i - K]:
        is_get_list.extend([False])
    else:
        is_get_list.extend([True])

for i in range(N):
    if not is_get_list[i]:
        continue
    if T[i] == 'r':
        ans += P
    if T[i] == 's':
        ans += R
    if T[i] == 'p':
        ans += S
print(ans)

Solution (Python):
import collections

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

T_count = collections.Counter(T)


point = T_count["r"]*P + T_count["s"]*R + T_count["p"]*S

for idx, t in enumerate(T):
    
    if idx + K >= N:
        break
    if t == T[idx+K]:
        if t == "r":
            point -= P
        elif t == "s":
            point -= R
        elif t == "p":
            point -= S
        T[idx+K] = "x"
print(point)

Solution (Python):
import sys

input = sys.stdin.readline


class AtCoder:
    def main(self):
        N, K = map(int, input().split())
        R, S, P = map(int, input().split())
        T = input().rstrip()

        jyanken = {'r': 'p', 's': 'r', 'p': 's'}

        win = []
        for t in T:
            win.append(jyanken[t])

        pointer = len(T) - 1
        while pointer - K >= 0:
            if win[pointer] == win[pointer - K]:
                win[pointer - K] = 'x'
            pointer -= 1

        points = {'r': R, 's': S, 'p': P, 'x': 0}
        ans = 0
        for w in win:
            ans += points[w]

        print(ans)



if __name__ == '__main__':
    AtCoder().main()

Solution (Python):
from collections import deque

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

hands = deque()
score = 0
for i in range(N):
    hand = {'r': 'p', 's': 'r', 'p': 's'}[T[i]]

    if len(hands) == K:
        last = hands[0]
        if last == hand:
            hand = '*'
        hands.popleft()
    hands.append(hand)

    score += {'r': R, 's': S, 'p': P}.get(hand, 0)
print(score)

Solution (Python):
from collections import deque

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

p_table = {"r": P, "s": R, "p": S}
h_table = {"r": "p", "s": "r", "p": "s"}
hist = deque(maxlen=K)
point = 0
for i, t in enumerate(T, 1):
    if i <= K or h_table[t] != hist[0]:
        point += p_table[t]
        hist.append(h_table[t])
    else:
        hist.append("_")
    

print(point)

Solution (Python):
if __name__ == "__main__":
	N, K = map(int, input().split())
	R, S, P = map(int, input().split())
	T = input()
	point = {"r": P, "s": R, "p": S}
	ans = 0
	for i in range(K):
		flag = False
		idx = i
		ans += point[T[idx]]
		while idx + K < N:
			prev_idx = idx
			idx = idx + K
			if T[prev_idx] != T[idx]:
				ans += point[T[idx]]
				flag = False
			else:
				if flag:
					ans += point[T[idx]]
					flag = False
				else:
					flag = True

	print(ans)

Solution (Python):
n, k = map(int, input().split())
r, s, p = map(int, input().split())
pointMap = {
  'r': p, 's': r, 'p': s
}

t = input()

pointSum = 0
preList = ['x'] * k 

for i, c in enumerate(t):
  if preList[i % k] == c:
    preList[i % k] = 'x'
    continue
  pointSum += pointMap[c]
  preList[i % k] = c

print(pointSum)

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

ans = 0

H = [""] * N


def win(i, t):
    if t == "r":
        return P
    elif t == "s":
        return R
    else:
        return S


for i in range(N):
    if T[i] == "r":
        H[i] = "p"
    elif T[i] == "s":
        H[i] = "r"
    else:
        H[i] = "s"

for i in range(K, N):
    if H[i] == H[i-K]:
        H[i] = ""

for i in range(N):
    if H[i] == "r":
        ans += R
    elif H[i] == "s":
        ans += S
    elif H[i] == "p":
        ans += P


print(ans)

Solution (Python):
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=list(input())
L=[[] for i in range(k)]

for i in range(n):
  L[i%k].append(t[i])

ans=0
for i in range(k):
  dp=[[0]*3 for i2 in range(len(L[i])+1)]
  for j in range(1,len(L[i])+1):
    dp[j][0]=max(dp[j-1][1],dp[j-1][2])
    if L[i][j-1]=='s':
      dp[j][0]+=r
    dp[j][1]=max(dp[j-1][0],dp[j-1][2])
    if L[i][j-1]=='r':
      dp[j][1]+=p
    dp[j][2]=max(dp[j-1][0],dp[j-1][1])
    if L[i][j-1]=='p':
      dp[j][2]+=s
  ans+=max(dp[len(L[i])])
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline

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


ret = 0
cur_my_hand = []
ca = cur_my_hand.append
for i,v in enumerate(t):
    if i < k:
        if v == "r":
            ret+=p
            ca("p")
        elif v == "s":
            ret+=r
            ca("r")
        elif v == "p":
            ret+=s
            ca("s")
    else:
        if v == "r" and cur_my_hand[i-k]!="p":
            ret+=p
            ca("p")
        elif v == "s" and cur_my_hand[i-k]!="r":
            ret+=r
            ca("r")
        elif v == "p" and cur_my_hand[i-k]!="s":
            ret+=s
            ca("s")
        else:
            ca("o")
print(ret)

Solution (Python):
from collections import Counter
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
T2RSP = {'r':P, 's':R, 'p':S}
ans = 0
for i, t in enumerate(T):
    ans += T2RSP[t]
for k in range(K):
    partT = T[k+K::K]
    pre_t = T[k]
    count = 1
    for t in partT:
        if pre_t == t:
            count += 1
        else:
            ans -= T2RSP[pre_t] * (count // 2)
            pre_t = t
            count = 1
    if count >= 2:
        ans -= T2RSP[pre_t] * (count // 2)


print(ans)

Solution (Python):
n,k = map(int,input().split())
r,s,p = map(int,input().split())
t = list(str(input()))
cntr = t.count("r")
cnts = t.count("s")
cntp = t.count("p")
cntr0 = 0
cnts0 = 0
cntp0 = 0
ans = 0

for i in range(n-k):
    if t[i] == "r"and t[i] == t[i+k]:
        cntr0 += 1
        t[i+k] = "q"
    elif t[i] == "s"and t[i] == t[i+k]:
        cnts0 += 1
        t[i+k] = "q"
    elif t[i] == "p"and t[i] == t[i+k]:
        cntp0 += 1
        t[i+k] = "q"

ans = p*(cntr - cntr0) + r*(cnts - cnts0) + s*(cntp - cntp0)
print(ans)

Solution (Python):
N, K = map(int, input().split(" "))
R, S, P = map(int, input().split(" "))
T = list(input())
te = [""] * N
kinsi = ''
score = 0
for i in range(N):
    if i >= K:
        kinsi = te[i-K]
    if T[i] == 'r':
        if kinsi != 'p':
            te[i] = 'p'
            score += P
        else:
            te[i] = ''
    if T[i] == 's':
        if kinsi != 'r':
            te[i] = 'r'
            score += R
        else:
            te[i] = ''
    if T[i] == 'p':
        if kinsi != 's':
            te[i] = 's'
            score += S
        else:
            te[i] = ''
print(score)

Solution (Python):

import numpy as np
import sys
sys.setrecursionlimit(100000)


def acinput():
    return list(map(int, input().split(" ")))

N,K=acinput()
R,S,P=acinput()
T=list(input())

score={}
score["r"]=R
score["s"]=S
score["p"]=P
op={}
op["r"]="p"
op["s"]="r"
op["p"]="s"

hand=[-1]*N
res=0



for i in range(len(T)):
    if i>=K:
        if hand[i-K]!=op[T[i]]:
            res+=score[op[T[i]]]
            hand[i] = op[T[i]]
    else:
        res += score[op[T[i]]]
        hand[i]=op[T[i]]

print(res)

Solution (Python):
from collections import deque

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

score = deque()

for i in range(len(T)):
    if T[i] == "r":
        score.append(P)
    elif T[i] == "s":
        score.append(R)
    elif T[i] == "p":
        score.append(S)

for i in range(len(score)-K):
    if T[i] == T[i+K]:
        if score[i] >= score[i+K]:
            score[i+K] = 0
        else:
            score[i] = 0

print(sum(score))

Solution (Python):
import sys
sys.setrecursionlimit(4100000)

n,k= [int(i) for i in input().split()]
pts = {}
pts["s"],pts["p"],pts["r"] = [int(i) for i in input().split()]
t = input()
take,notake, chose = [0 for _ in range(n)], [0 for _ in range(n)], ["w" for _ in range(n)]
for i in range(len(t)):
    if i == 0:
        take[0] = pts[t[i]]
        notake[0] = 0
        chose[0] = t[i]
    else:
        if t[i] == chose[i-k]:
            take[i] = max(take[i-1],notake[i-1])
            notake[i] = max(take[i-1],notake[i-1])
        else:
            take[i] = take[i-1] + pts[t[i]]
            notake[i] = max(take[i-1],notake[i-1])
            chose[i] = t[i]
print(max(take[-1],notake[-1]))

Solution (Python):
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)]
        rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()

input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

ans=0

n,k=LI()
r,s,p=LI()
t=input()
m=list('rsp')
a=[p,r,s]
dc=dict(zip(m,a))
z=[]
for i in range(k):
    z.append(''.join(t[i::k]))
for zz in z:
    pre=None
    for zzz in zz:
        if pre!=zzz:
            ans+=dc[zzz]
            pre=zzz
        else:
            pre=None

print(ans)

Solution (Python):

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

for i in range(N):
    if T[i]=="r":
        if i>=K:
            if T[i-K]==T[i]:
                T[i]="o"
            else:
                ans+=P
        else:
            ans+=P
    elif T[i]=="s":
        if i>=K:
            if T[i-K]==T[i]:
                T[i]="o"
            else:
                ans+=R
        else:
            ans+=R
    elif T[i]=="p":
        if i>=K:
            if T[i-K]==T[i]:
                T[i]="o"
            else:
                ans+=S
        else:
            ans+=S

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    N, K = map(int, input().split())
    R, S, P = map(int, input().strip().split())
    T = input().strip()

    i = 0
    score = 0
    while i != K:
        before = ""
        
        for c in T[i::K]:
            
            if c != before:
                if c == 'r':
                    score += P
                elif c == 's':
                    score += R
                else:
                    score += S
                before = c
            else:
                before = ""
                
        i += 1
    print(score)
if __name__ == '__main__':
    main()

Solution (Python):
def main():
    N,K=map(int,input().split())
    R,S,P=map(int,input().split())
    T=input()
    L=['']*N
    score=0
    for i in range(N):
        if T[i]=='r':
            if i>=K and L[i-K]=='p':
                pass
            else:
                score+=P
                L[i]='p'
        elif T[i]=='s':
            if i>=K and L[i-K]=='r':
                pass
            else:
                score+=R
                L[i]='r'
        else:
            if i>=K and L[i-K]=='s':
                pass
            else:
                score+=S
                L[i]='s'
    print(score)


main()

Solution (Python):
N,K = map(int,input().split())
R,S,P = map(int,input().split())
T = list(input())
A = 0
rsp = {
    "r":P,
    "s":R,
    "p":S,
}
A += T.count("r")*P
A += T.count("s")*R
A += T.count("p")*S
a = []
for i in range(N):
    if i-K >= 0 and T[i] == a[i-K]:
        A -= rsp[T[i]]
        a.append("")
    else:
        a.append(T[i])
print(A)

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

score=0

def point(c):
    if c == 'r':
        return p
    if c == 's':
        return r
    if c == 'p':
        return s
    

draw = [False for i in range(n)]

for i in range(n):
    if i < k or t[i] != t[i-k]:
        score += point(t[i])
    elif t[i] == t[i-k]:
        if draw[i-k]:
            score += point(t[i])
        else:
            draw[i] = True    
    
print(score)

Solution (Python):
N,K=map(int,input().split())
R,S,P=map(int,input().split())
T=input()
a=0
for i in range(K):
    t=0
    l=T[i:N:K]
    for j in l:
        if j=="r":
            if t!=1:
                a+=P
                t=1
            else:
                t=0
        if j=="s":
            if t!=2:
                a+=R
                t=2
            else:
                t=0
        if j=="p":
            if t!=3:
                a+=S
                t=3
            else:
                t=0
print(a)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def f(c):
        if c == "r":
            return 0
        elif c == "s":
            return 1
        return 2
    def g(i,j):
        if (i+1)%3 == j:
            return 1
        return 0
    n,K = LI()
    r = LI()
    t = input()
    t = [f(i) for i in t]
    c = [1]*n
    ans = 0
    for i in range(n):
        if not c[i]:
            continue
        j = i
        l = []
        while j < n:
            l.append(j)
            c[j] = 0
            j += K
        dp = [[0]*3 for j in range(len(l))]
        for j in range(3):
            li = t[l[0]]
            dp[0][j] = r[j]*g(j,li)
        for j in range(1,len(l)):
            nj = j-1
            cj = t[l[j]]
            for k in range(3):
                q = r[k]*g(k,cj)
                for m in range(3):
                    if k == m:
                        continue
                    nd = dp[nj][m]+q
                    if dp[j][k] < nd:
                        dp[j][k] = nd

        ans += max(dp[-1])
    print(ans)
    return


if __name__ == "__main__":
    solve()

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

out=0
te=''
for i in range(k):
  if t[i]=='r':
    out+=p
    te+='p'
  elif t[i]=='s':
    out+=r
    te+='r'
  else:
    out+=s
    te+='s'
    
for i in range(k, n):
  if t[i]=='r':
    if te[i-k]=='p':
      te+='n'
    else:
      te+='p'
      out+=p
  elif t[i]=='s':
    if te[i-k]=='r':
      te+='n'
    else:
      te+='r'
      out+=r
  else:
    if te[i-k]=='s':
      te+='n'
    else:
      te+='s'
      out+=s
      
print(out)

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

hoge = {i: t[i::k] for i in range(k)}
score_map = {"r": p, "s": r, "p": s}

ans = 0
for i in range(k):
  prev_hand = None
  for hand in hoge[i]:
    if hand != prev_hand:
      ans += score_map[hand]
      prev_hand = hand 
    else:
      prev_hand = None

print(ans)

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

dp = []
for i in range(N):
    if i < K:
        if T[i] == "s":
            dp.append([R, 0, 0])
        elif T[i] == "p":
            dp.append([0, S, 0])
        else:
            dp.append([0, 0, P])
    else:
        dpi = dp[-K]
        maxdpi = max(dpi)
        if T[i] == "s":
            dp.append([max(dpi[1], dpi[2]) + R, maxdpi, maxdpi])
        elif T[i] == "p":
            dp.append([maxdpi, max(dpi[0], dpi[2]) + S, maxdpi])
        else:
            dp.append([maxdpi, maxdpi, max(dpi[0], dpi[1]) + P])

ans = sum(max(dp[i]) for i in range(N - K, N))
print(ans)

Solution (Python):
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=input()
ans=0
ta=''
for i in range(n):
    if t[i]=='r':
        if i<k or ta[i-k]!='p':
            ans+=p
            ta+='p'
        else:
            ta+='*'
    elif t[i]=='s':
        if i<k or ta[i-k]!='r':
            ans+=r
            ta+='r'
        else:
            ta+='*'
    elif t[i]=='p':
        if i<k or ta[i-k]!='s':
            ans+=s
            ta+='s'
        else:
            ta+='*'
print(ans)

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

win = {"r":"p", "s":"r", "p":"s"}  
points = {"r":R, "s":S, "p":P}  

hands = []
ans = 0

for i in range(N):
    if i < K:
        hands.append(str(win[T[i]]))
        ans += points[str(win[T[i]])]
    elif str(win[T[i]]) == hands[-K]:
        hands.append("n")
    else:
        hands.append(str(win[T[i]]))
        ans += points[str(win[T[i]])]

print(ans)

Solution (Python):
N,K=map(int,input().split())
R,S,P=map(int,input().split())
T=input()
A=[]
for x in T:
    if x == 's':
        A.append('r')
    if x == 'p':
        A.append('s')
    if x == 'r':
        A.append('p')

for i in range(K,N):
    if A[i-K] == A[i]:
        A[i] = 'x'

ans = 0
for x in A:
    if x == 's':
        ans += S
    if x == 'p':
        ans += P
    if x == 'r':
        ans += R
print(ans)

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

t_ls=list(t)
ls=[]
for i,hand in enumerate(t_ls):
    try:
        if hand == "r":
            t_ls[i] = "p"
        elif hand == "s":
            t_ls[i] = "r"
        elif hand == "p":
            t_ls[i] = "s"
        if t_ls[i+k] == hand:
            t_ls[i+k] = "*"
    except:
        pass

ans = 0
for i in t_ls:
    if i == "r":
        ans+=r
    elif i == "s":
        ans+=s
    elif i == "p":
        ans+=p
print(ans)

Solution (Python):
N,K = map(int,input().split())
R,S,P = map(int,input().split())
T = input()
ans = 0
for i in range(K):
    k = i
    if T[k]=='r':
        ans += P
    elif T[k]=='s':
        ans += R
    else:
        ans += S
    flag = False
    while k < N:

        if k+K < N:
            if T[k+K]!=T[k]:
                if T[k+K]=='r':
                    ans += P
                elif T[k+K]=='s':
                    ans += R
                else:
                    ans += S
                flag = False
            else:
                if not flag:
                    flag = True
                else:
                    flag = False

                    if T[k+K]=='r':
                        ans += P
                    elif T[k+K]=='s':
                        ans += R
                    else:
                        ans += S
        k += K
print(ans)

Solution (Python):
N, K = map(int, input().split())
R, S, P =map(int, input().split())
T = input().rstrip()
_mapping = {"r": P, "s": R, "p": S}
d = [None] * K
ans = 0
for i, t in enumerate(T):
    k = i % K
    if d[k] == t:
        d[k] = None
        continue
    else:
        d[k] = t
        ans += _mapping[t]
        continue
print(ans)

Solution (Python):
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

n, k = ril()
r, s, p = ril()
t = rs()

dic = {'r': p, 's': r, 'p': s}
ls = list(t)
lss = [ls[i::k] for i in range(k)]
res = 0
for ls in lss:
    prev = ls[0]
    res += dic[prev]
    for x in ls[1:]:
        if x != prev:
            res += dic[x]
            prev = x
        else:
            prev = None
print(res)