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):

import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

























def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

inf = float('inf')
mod = 1000000007



def main():
	N,K = inputMap()
	R,S,P = inputMap()
	T = input()
	T = T[:-1]

	ans = 0
	hantei = {}
	hantei["r"] = R
	hantei["s"] = S
	hantei["p"] = P

	TE = [[] for i in range(K)]
	cnts = 0
	for s in T:
		tmp = ""
		if s == "r":
			tmp = "p"
		elif s == "s":
			tmp = "r"
		else:
			tmp = "s"
		TE[cnts].append(tmp)
		cnts += 1
		cnts %= K

	for i,val in enumerate(TE):
		flg = False
		for j, vol in enumerate(val):
			if flg == False:
				ans += hantei[vol]
			else:
				flg = False
				continue

			if j == len(val)-1:
				break

			if vol == val[j+1]:
				flg = True

	print(ans)







def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res


def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y



def H(n, r, mod=10**9+7):
	
	
    return combination(n+r-1, r, mod)

class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        
        
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

if __name__ == "__main__":
	main()

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

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

    
    point = {'p': s, 'r': p, 's': r}
    prevhand = ['o'] * k
    score = 0

    for i in range(n):
        if i + 1 <= k:
            prevhand[i%k] = t[i]
            score += point[t[i]]
        elif prevhand[i%k] != t[i]:
            prevhand[i%k] = t[i]
            score += point[t[i]]
        else:
            prevhand[i%k] = 'o'

    print(score)

if __name__ == '__main__':
    main()

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

hand = {'r':p, 's':r, 'p':s}
win = {'r':'p', 's':'r', 'p':'s'}

ans = 0
u = []
for i,tt in enumerate(t):
    if i >= k and tt == t[i-k] and u[i-k] == win[tt]:
            u.append(tt)
    else:
        u.append(win[tt])
        ans += hand[tt]
print(ans)

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

res = [0]*N
hands = ["r", "s", "p"]

for i in range(N):
    res[i] = hands[hands.index(T[i])-1]

for i in range(N):
    if i >= K and res[i-K] == res[i]:
        res[i] = 0

score = R*res.count("r") + S*res.count("s") + P*res.count("p")
print(score)

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

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


ans = 0
memo = []

for i in range(n):
  if i < k:
    ans += scores[T[i]]
    memo.append(T[i])
  else:
    if memo[i-k] == T[i]:
      memo.append('N')
    else:
      ans += scores[T[i]]
      memo.append(T[i])
print(ans)

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

score =[]
for i in range(n):
    enemy = t[i]
    if i - k >= 0 and t[i - k] == enemy and score[i-k]:
        score.append(0)
    else:
        score.append(win[enemy])
print(sum(score))

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


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


for i in range(K):
    if T[i] == 's':
        dp[i][0] = R
    elif T[i] == 'p':
        dp[i][1] = S
    else:
        dp[i][2] = P

for i in range(K, N):
    k = i % K
    if T[i] == 's': 
        dp[k][0], dp[k][1], dp[k][2] = max(dp[k][1], dp[k][2]) + R, max(dp[k][0], dp[k][2]), max(dp[k][0], dp[k][1])
    elif T[i] == 'p': 
        dp[k][0], dp[k][1], dp[k][2] = max(dp[k][1], dp[k][2]), max(dp[k][0], dp[k][2]) + S, max(dp[k][0], dp[k][1])
    else:
        dp[k][0], dp[k][1], dp[k][2] = max(dp[k][1], dp[k][2]), max(dp[k][0], dp[k][2]), max(dp[k][0], dp[k][1]) + P
    
ans = 0
for tmp in dp:
    ans += max(tmp)

print (ans)

Solution (Python):
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)


def get_nums_l():
    return [ int(s) for s in input().split(" ")]


def get_nums_n(n):
    return [ int(input()) for _ in range(n)]


def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

def wins(c):
    if c == "r":
        return "p"
    elif c == "s":
        return "r"
    else:
        return "s"

n,k = get_nums_l()
r,s,p = get_nums_l()
point = {
    "r": r,
    "s": s,
    "p": p
}
t = input()

won = [False] * n

ans = 0
for i,c in enumerate(t):
    if i >= k and t[i-k] == c and won[i-k]:
        
        
        pass
    else:
        
        won[i] = True
        ans += point[wins(c)]

print(ans)

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

Ts=[[] for _ in range(K)]
for i in range(N):
    Ts[i%K]+=T[i]

def sub(L):
    L.append(0)
    pre = 0
    s=0
    for i in range(len(L)-1):
        if pre != L[i]:
            if L[i] == "r":
                s+=P
            elif L[i] == 's':
                s+=R
            else:
                s+=S
            pre=L[i]
        else:
            if L[i+1]!='r':
                pre='r'
            elif L[i+1]!='s':
                pre='s'
            else:
                pre='p'
    return s

s=0
for t in Ts:
    s+=sub(t)
print(s)

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
ans = 0
flg = 0
val = {'r': P, 's': R, 'p': S}
for i in range(K):
    for j in range(i,N,K):
        if j == i:
            ans += val[T[j]]
            flg=0
        else:
            if T[j] == T[j-K]:
                if flg == 0:
                    flg = 1
                else:
                    ans += val[T[j]]
                    flg = 0
            else:
                ans += val[T[j]]
                flg = 0
print(ans)

Solution (Python):
def main(N,K,R,S,P,T):
    T_takahashi = T.replace('r','x').replace('s','y').replace('p','z').replace('x','p').replace('y','r').replace('z','s')
    ans = 0
    i = 0
    for i in range(N):
        if i+K <= N-1:
            if T_takahashi[i] in 'spr' and T_takahashi[i] == T_takahashi[i+K]:
                T_takahashi = T_takahashi[:i+K] + T_takahashi[i+K].replace(T_takahashi[i], 'w') + T_takahashi[i+K+1:]
    for hand in T_takahashi:
        if hand == 'r':
            ans += R
        elif hand == 's':
            ans += S
        elif hand == 'p':
            ans += P
        else:
            ans += 0
    return ans

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

Solution (Python):
from collections import Counter
from collections import defaultdict

def main(n,k,r,s,p,t):
    score = 0
    for i in range(len(t)):
        if i < k:
            continue
        if t[i] == t[i-k]:
            t[i] = "N"
    c = Counter(t)
    i = defaultdict(int,c)
    score += i["r"]*p + i["s"]*r + i["p"]*s
    return score
    
n,k = map(int, input().split())
r,s,p = map(int, input().split())
t = list(input())
print(main(n,k,r,s,p,t))

Solution (Python):
n,k = map(int,input().split())
r,s,p = map(int,input().split())
t = input()
score = {'r':p, 's':r ,'p':s}
from collections import deque
past = deque([])

ans = 0
for i in range(n):
  if i < k:
    ans += score[t[i]]
    past.append(t[i])
  else:
    if past.popleft() != t[i]:
      ans += score[t[i]]
      past.append(t[i])
    else:
      past.append('nn')
      
  
print(ans)

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

flag = [0] * N
score = 0
for i in range(N):
    if i >= K and flag[i-K] == 0 and T[i] == T[i-K]:
        flag[i] = 1
        continue
    if T[i] == 'r':
        score += P
    if T[i] == 's':
        score += R
    if T[i] == 'p':
        score += S
print(score)

Solution (Python):
N, K = map(int, input().split())
s,p,r = map(int, input().split())
point={'s':s, 'p':p, 'r':r}

T = input()

group = [[] for i in range(K)]

for i in range(N):
    group[i%K].append(T[i])
    
def score(l):
    s=0
    ex = ''
    for i in l:
        if ex == i:
            ex =''
        else:
            s += point[i]
            ex = i
    return s

ans = 0
            
for sub in group:
    ans += score(sub)

print(ans)

Solution (Python):
import numpy as np
n, k = map(int, input().split())
r, s, p = map(int, input().split())
T = np.array(list(input()))

ans = 0
for i in range(k):
  sli = T[list(range(i, n, k))]
  rc = sc = pc = 0
  for t in sli:
    if t == 'r':
      if rc+sc != 0:
        ans += (rc+1)//2 * r + (sc+1)//2 * s
        rc = sc = 0
      pc += 1
    elif t == 's':
      if sc+pc != 0:
        ans += (sc+1)//2 * s + (pc+1)//2 * p
        sc = pc = 0
      rc += 1
    elif t == 'p':
      if rc+pc !=0:
        ans += (rc+1)//2 * r + (pc+1)//2 * p
        rc = pc = 0
      sc += 1
      
  if rc+sc+pc != 0:
    ans += (rc+1)//2 * r + (sc+1)//2 * s + (pc+1)//2 *p
   
print(ans)

Solution (Python):
n,k=map(int,input().split())
scores=list(map(int,input().split()))
t=input()
winner={'r':2,'s':0,'p':1}
ans=0
for i in range(k):
  ts=''
  for j in range(n):
    if k*j+i>=n:
      break
    ts+=t[k*j+i]
  ts+='?'
  l=len(ts)
  hand=ts[0]
  cnt=1
  for j in range(1,l):
    if hand==ts[j]:
      cnt+=1
    else:
      ans+=scores[winner[hand]]*((cnt+1)//2)
      hand=ts[j]
      cnt=1
print(ans)

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

def calc(te):
   if te=="r":
      point=p
   elif te=="s":
      point=r
   else:
      point=s
   return point

ans=0
L=[]
for i in range(n):
   if i>=k and t[i]==L[i-k]:
      L.append("b")
      continue
   else:
      ans+=calc(t[i])
      L.append(t[i])
print(ans)

Solution (Python):
import sys
import socket

hostname = socket.gethostname()

if hostname == 'F451C':
    sys.stdin = open('d1.in')


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


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


def read_int():
    return int(input())


def read_str():
    return input()


def solve(t, R, S, P):
    n = len(t)
    m = [[0] * 3 for i in range(n)]
    m[0][0] = R if t[0] == 's' else 0
    m[0][1] = S if t[0] == 'p' else 0
    m[0][2] = P if t[0] == 'r' else 0

    for i in range(1, n):
      m[i][0] = max(m[i-1][1], m[i-1][2])
      m[i][0] += R if t[i] == 's' else 0
      m[i][1] = max(m[i-1][0], m[i-1][2])
      m[i][1] += S if t[i] == 'p' else 0
      m[i][2] = max(m[i-1][0], m[i-1][1])
      m[i][2] += P if t[i] == 'r' else 0

    return max([m[n-1][0], m[n-1][1], m[n-1][2]])


def bigger(l):
  if l == 'r':
    return 'p'
  if l == 'p':
    return 's'
  if l == 's':
    return 'r'


def solve_greedy(t, R, S, P):
    n = len(t)
    res = 0
    l = ''
    score = {'r': R, 's': S, 'p': P}
    for i in range(n):
      for k in 'rps':
        if t[i] == k:
          if l != bigger(k):
            l = bigger(k)
            res += score[bigger(k)]
          else:
            for q in 'rps':
              if q != bigger(k):
                if i+1 < n and bigger(t[i+1]) != q:
                  l = q
    return res


def main():
    N, K = read_int_list()
    R, S, P = read_int_list()
    T = read_str()

    res = 0
    for i in range(K):
      
      res += solve_greedy(T[i::K], R, S, P)
    
    print(res)


main()

Solution (Python):
import sys
import socket

hostname = socket.gethostname()

if hostname == 'F451C':
    sys.stdin = open('d1.in')


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


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


def read_int():
    return int(input())


def read_str():
    return input()


def solve(t, R, S, P):
    n = len(t)
    m = [[0] * 3 for i in range(n)]
    m[0][0] = R if t[0] == 's' else 0
    m[0][1] = S if t[0] == 'p' else 0
    m[0][2] = P if t[0] == 'r' else 0

    for i in range(1, n):
      m[i][0] = max(m[i-1][1], m[i-1][2])
      m[i][0] += R if t[i] == 's' else 0
      m[i][1] = max(m[i-1][0], m[i-1][2])
      m[i][1] += S if t[i] == 'p' else 0
      m[i][2] = max(m[i-1][0], m[i-1][1])
      m[i][2] += P if t[i] == 'r' else 0

    return max([m[n-1][0], m[n-1][1], m[n-1][2]])


def main():
    N, K = read_int_list()
    R, S, P = read_int_list()
    T = read_str()

    res = 0
    for i in range(K):
      res += solve(T[i::K], R, S, P)
    
    print(res)


main()

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

def point(str1,str2): 
    if str1=="s" and str2=="r":
        return R
    elif str1=="r" and str2=="p":
        return P
    elif str1=="p" and str2=="s":
        return S
    else:
        return 0

T=[[] for i in range(K)]

for i in range(N):
    T[i%K].append(Ti[i])

ans=0
for i in range(K):
    L=len(T[i])
    DP=[[0]*3 for i in range(L+1)]
    for j in range(L):
        DP[j+1][0]=max(DP[j][1],DP[j][2])+point(T[i][j],"r")
        DP[j+1][1]=max(DP[j][2],DP[j][0])+point(T[i][j],"s")
        DP[j+1][2]=max(DP[j][0],DP[j][1])+point(T[i][j],"p")
    ans += max(DP[L])

print(ans)

Solution (Python):
from collections import defaultdict
N, K = map(int, input().split())
r, s, p = map(int, input().split())
score = {}
score['s'] = r
score['p'] = s
score['r'] = p
T = input()
dic = defaultdict(int)
ans = 0
for i in range(N):
  c = T[i]
  if i<K:
    ans += score[c]
    dic[i] = c
    continue
  d = dic[i%K]
  if d==c:
    dic[i%K] = 0
    continue
  ans += score[c]
  dic[i%K] = c
print(ans)

Solution (Python):
n, k = (int(x) for x in input().split())
r, s, p = (int(x) for x in input().split())
t = input()
ans = 0
flg = [0] * k
for i in range(n):
    if t[i] == 'r':
        v = p
    elif t[i] == 's':
        v = r
    else:
        v = s
    if i < k:
        ans += v
    else:
        if t[i] == t[i - k]:
            if flg[i % k] == 0:
                flg[i % k] = 1
            else:
                ans += v
                flg[i % k] = 0
        else:
            ans += v
            flg[i % k] = 0
print(ans)

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

j_l = "rsp"
kachi = lambda k : j_l[ (j_l.find(T[k]) + 2) % 3 ]

rireki = []
score = [0,0,0] 

for i in range(N): 
  if i-K >= 0: 
    if kachi(i) != rireki[i-K]: 
      score[ (j_l.find(T[i])+ 2) % 3 ] += 1
      rireki.append(kachi(i)) 
      
    else: 
      rireki.append("hikiwake_or_make") 
      
  else: 
    score[ (j_l.find(T[i])+ 2) % 3 ] += 1 
    rireki.append(kachi(i)) 
    
tortal_score = R*score[0] + S*score[1] + P*score[2]



print(tortal_score)

Solution (Python):
from math import ceil

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

rows, cols = ceil(n / k), k
ans = 0
for j in range(cols):
    dp = [[0, 0, 0] for _ in range(rows + 1)]
    for i in range(rows):
        ri, si, pi = dp[i]
        if i * k + j < n:
            c = t[i * k + j]
        else:
            c = ''
        dp[i + 1][0] = max(si, pi) + r * (c == 's')
        dp[i + 1][1] = max(pi, ri) + s * (c == 'p')
        dp[i + 1][2] = max(ri, si) + p * (c == 'r')
    ans += max(dp[rows])

print(ans)

Solution (Python):
import sys
import math
from collections import deque
import copy

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

SUM = 0

for i in range(1, K + 1):
    p = 0
    t = []
    for l in range(10 ** 9):
        t.append(T[i + K * l - 1])
        if (i + K * (l + 1) -1 ) >= N:
            break
    dp = [[-1, -1, -1] for _ in range(len(t) + 1)]
    dp[0] = [0, 0, 0]
    for l in range(1, len(t) + 1):
        if t[l - 1] == "r":
            dp[l][0] = max(dp[l - 1][1], dp[l - 1][2])
            dp[l][1] = max(dp[l - 1][0], dp[l - 1][2])
            dp[l][2] = max(dp[l - 1][0], dp[l - 1][1]) + P
        elif t[l - 1] == "s":
            dp[l][0] = max(dp[l - 1][1], dp[l - 1][2]) + R
            dp[l][1] = max(dp[l - 1][0], dp[l - 1][2])
            dp[l][2] = max(dp[l - 1][0], dp[l - 1][1])
        else:
            dp[l][0] = max(dp[l - 1][1], dp[l - 1][2])
            dp[l][1] = max(dp[l - 1][0], dp[l - 1][2]) + S
            dp[l][2] = max(dp[l - 1][0], dp[l - 1][1])
    SUM += max(dp[len(t)])
print(SUM)

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
pt_dict = {"r":P, "s":R, "p":S}
pt = 0
result = []
for i in range(N):
    if i <K:
        pt += pt_dict[T[i]]
        result.append("win")
    elif T[i] == T[i-K] and result[i-K]=="win":
            result.append("lose")
    else:
        pt += pt_dict[T[i]]
        result.append("win")
print(pt)

Solution (Python):
from itertools import groupby

N,K=map(int,input().split())
R,S,P=map(int,input().split())
T=input()
ans=0
X=[[] for i in range(0,K)]
for i in range(0,N):
    X[i%K].append(T[i])
for i in range(0,K):
    X[i]=groupby(X[i])
    for key,group in X[i]:
        g=len(list(group))
        if key=='r':
            ans+=P*((g+1)//2)
        elif key=='s':
            ans+=R*((g+1)//2)
        else:
            ans+=S*((g+1)//2)
print(ans)

Solution (Python):
from array import array
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = array("u", list(input()))

for i in range(k, n):
    if t[i] == t[i-k]:
        t[i] = "*"

ans = (t.count("r") * p +
       t.count("s") * r +
       t.count("p") * s)

print(ans)

Solution (Python):
from array import array
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = array("u", list(input()))

for i in range(k, n-1):
    if t[i] == t[i-k]:
        t[i] = "*"
        
if t[n-1] == t[n-1-k]:
    t[n-1] = "*"

ans = (t.count("r") * p +
       t.count("s") * r +
       t.count("p") * s)

print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(1000000000)
import math
from fractions import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7

def meg(f, ok, ng):
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if f(mid):
            ok=mid
        else:
            ng=mid
    return ok

def get_inv(n, modp):
    return pow(n, modp-2, modp)

def factorials_list(n, modp):    
    fs = [1]
    for i in range(1, n+1):
        fs.append(fs[-1] * i % modp)
    return fs

def invs_list(n, fs, modp):     
    invs = [get_inv(fs[-1], modp)]
    for i in range(n, 1-1, -1):
        invs.append(invs[-1] * i % modp)
    invs.reverse()
    return invs

def comb(n, k, modp):
    vn = vk = vn_k = 1
    for i in range(1, n+1):
        vn = vn * i % modp
        if i == k:
            vk = vn
        if i == n-k:
            vn_k = vn
    return vn * get_inv(vk, modp) * get_inv(vn_k, modp) % modp

def comb_from_list(n, k, modp, fs, invs):   
    return fs[n] * invs[n-k] * invs[k] % modp



def main():
    N,K=mis()
    R,S,P=mis()
    T=input()
    
    ans = 0
    for i in range(K):
        r,s,p = 0,0,0
        for t in T[i::K]:
            r,s,p = max(s, p), max(r, p), max(r, s)
            if t=='r':
                p += P
            elif t=='s':
                r += R
            else:
                s += S
        ans += max(r,s,p)
    print(ans)

main()

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

from collections import deque
que = deque([])

ans = 0
for i in range(n):
    if i >= k:
        pre = que.popleft()
        if t[i] == 'r':
            if pre == 'p':  
                que.append('')  
            else:
                que.append('p')
                ans += p
        elif t[i] == 's':
            if pre == 'r':
                que.append('')
            else:
                que.append('r')
                ans += r
        elif t[i] == 'p':
            if pre == 's':
                que.append('')
            else:
                que.append('s')
                ans += s 
    else:
        if t[i] == 'r':
            que.append('p')
            ans += p
        elif t[i] == 's':
            que.append('r')
            ans += r
        elif t[i] == 'p':
            que.append('s')
            ans += s
print(ans)

Solution (Python):
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = list(input())
lr, ls, lp = -n, -n, -n
ans = 0

for i in range(k):
    if t[i] == "r":
        ans += p
    elif t[i] == "s":
        ans += r
    else:
        ans += s
for i in range(k,n):
    if t[i] == "r" and t[i-k] != "r":
        ans += p
    elif t[i] == "s" and t[i-k] != "s":
        ans += r
    elif t[i] == "p" and t[i-k] != "p":
        ans += s
    else:
        t[i] = "2"

print(ans)

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = list(input())
score = {'r': P, 'p': S, 's': R}
ans = 0

for i in range(K):
    flag = True

    while i < N:
        if i >= K and T[i] == T[i-K]:
            flag = not flag
        else:
            flag = True

        if flag:
            ans += score[T[i]]

        i += K

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(n):
  if t[i] == 'r':
    l.append(p)
  elif t[i] == 's':
    l.append(r)
  else:
    l.append(s)

score=sum(l)
for j in range(k,n):
  if t[j] == t[j-k]:
    t[j]='-'
    score-=l[j]

print(score)

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

ans_str = T.replace('r', 'a').replace('s', 'b').replace('p', 'c')
ans_str = list(ans_str.replace('a', 'p').replace('b', 'r').replace('c', 's'))

def rsp(arg):
    for x in 'rsp':
        if x not in arg: break
    return x

for i_str in range(K):
    idx = i_str
    while idx < len(ans_str):
        if idx > i_str:
            if ans_str[idx] == ans_str[idx - K]:
                if idx + K < len(ans_str):
                    ans_str[idx] = rsp((ans_str[idx - K], ans_str[idx + K]))
                else:
                    ans_str[idx] = rsp((ans_str[idx - K],))
        
        idx += K

ans = 0
for ansi, Ti in zip(ans_str, list(T)):
    if ansi == 'r' and Ti == 's':
        ans += R
    if ansi == 's' and Ti == 'p':
        ans += S
    if ansi == 'p' and Ti == 'r':
        ans += P

print(ans)

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

def point(aite):
    if aite == "r":
        return p
    elif aite == "s":
        return r
    else:
        return s

ten = 0
kako = ["o"]*k
for i in range(n):
    if kako[i%k] == t[i]:
        kako[i%k] = "o"
    else:
        kako[i%k] = t[i]
        ten += point(t[i])

print(ten)

Solution (Python):
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
a = {"r":p, "s":r, "p":s}
b = [1]*n
score = 0
for i in range(n):
  if i>k-1 and t[i]==t[i-k]:
    b[i] = 1-b[i-k]
  score += a[t[i]] if b[i]==1 else 0
print(score)

Solution (Python):
import math

N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
M = math.ceil(N/K)

H = [T[i::K] for i in range(K)]
res = 0
for h in H:
    dp = [[0]*3 for _ in range(len(h))]
    if h[0] == "r":
        dp[0][2] = P
    elif h[0] == "s":
        dp[0][0] = R
    else:
        dp[0][1] = S

    for i in range(1, len(h)):
        dp[i][0] = max(dp[i-1][1], dp[i-1][2])
        dp[i][1] = max(dp[i-1][0], dp[i-1][2])
        dp[i][2] = max(dp[i-1][0], dp[i-1][1])

        if h[i] == "r":
            dp[i][2] += P
        elif h[i] == "s":
            dp[i][0] += R
        else:
            dp[i][1] += S

    res += max(dp[-1])

print(res)

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

def score(c):
    if c == "r":
        return P
    if c == "s":
        return R
    if c == "p":
        return S

ans = 0

for i in range(N):
    if i < K:
        ans += score(T[i])
        memo[i] = 1
        continue
    if T[i] == T[i - K]:
        if memo[i - K] == 0:
            ans += score(T[i])
            memo[i] = 1
    else:
        ans += score(T[i])
        memo[i] = 1

print(ans)

Solution (Python):
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=input()
win_t=t.replace('r','P').replace('p','S').replace('s','R')

ans=''
cnt=0

for i in range(n):
  if i<k:
    ans+=win_t[i]
    continue
  if win_t[i]!=ans[i-k]:
    cnt+=1
    ans+=win_t[i]
  else:
    ans+='x'
    
print(ans.count('P')*p+ans.count('S')*s+ans.count('R')*r)

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

"""
Considering mod K, we may assume K = 1.
Thus we first consider this case.
"""
def func(hand):
    if hand == "r":
        return P
    elif hand == "s":
        return R
    elif hand == "p":
        return S
    else:
        return 0

def maxValue(lst):
    l = len(lst)
    score = 0
    prev = None
    repeat = 0

    for hand in lst:
        if prev != hand:
            if repeat % 2 == 1:
                score += func(prev) * (repeat + 1) // 2
            else:
                score += func(prev) * (repeat // 2 + 1)
            prev = hand
            repeat = 0
        else:
            repeat += 1
    if repeat % 2 == 1:
        score += func(lst[-1]) * (repeat + 1) // 2
    else:
        score += func(lst[-1]) * (repeat // 2 + 1)

    return score


ans = 0
for i in range(K):
    lst = []
    l = (N - 1 - i) // K
    for j in range(l + 1):
        lst.append(T[i + j * K])
    val = maxValue(lst)
    
    ans += val

print(ans)

Solution (Python):
import sys


def main():
    N,K = map(int,input().split())
    R,S,P = map(int,input().split())
    T = list(map(str,input()))
    d = {"s":R,"p":S,"r":P}
    s = {"s":"r","p":"s","r":"p"}
    ans = 0
    x = []
    for i in range(K):
        ans += d[T[i]]
        x.append(s[T[i]])

    for i in range(N-K):
        if (T[i] == T[K+i] and x[-K] == s[T[K+i]]):
            x.append(T[K+i])
        else:
            ans += d[T[K+i]]
            x.append(s[T[K+i]])
            
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
def win(t):
  if t == "g":
    return "p"
  if t == "c":
    return "g"
  if t == "p":
    return "c"

N, K = map(int, input().split())
G, C, P = map(int, input().split())
T = input().replace("r", "g").replace("s", "c")

point = {"g": G, "c": C, "p": P}

check = [None] * (N + K)
answer = 0
for i in range(N):
  w = win(T[i])
  if check[i] != w:
    answer += point[w]
    check[i + K] = w
    
print(answer)

Solution (Python):

n,k = map(int,input().split())
a = list(map(int,input().split()))
t = input()
raw = []
for i in range(n):
  if t[i] == 'r':
    raw.append(2)
  elif t[i] == 's':
    raw.append(0)
  else:
    raw.append(1)
ans = 0
result = []
for i in range(n):
  if i - k < 0:
    result.append(raw[i])
    ans += a[raw[i]]
  else:
    if raw[i] != result[i-k]:
      result.append(raw[i])
      ans += a[raw[i]]
    else:
      result.append(3)
print(ans)

Solution (Python):
n,k = map(int,input().split())
r,s,p = map(int,input().split())
t = input()
ans = 0
flag = []
for i in range(k):
    if t[i] == 'r':
        flag.append('r')
        ans += p
    elif t[i] == 's':
        flag.append('s')
        ans += r
    elif t[i] == 'p':
        flag.append('p')
        ans += s

for i in range(k,n):
    if flag[i-k] == t[i]:
        flag.append('')
        continue
    elif t[i] == 'r':
        flag.append('r')
        ans += p
    elif t[i] == 's':
        flag.append('s')
        ans += r
    elif t[i] == 'p':
        flag.append('p')
        ans += s

print(ans)