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):
from itertools import groupby

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

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

ans = 0
for i in range(K):
    A = T[i::K]
    ans += sum((len(tuple(v)) + 1) // 2 * C[k] for k, v in groupby(A))

print(ans)

Solution (Python):

import sys


def solve(N: int, K: int, R: int, S: int, P: int, T: str):
    memo = [""]*N

    for i in range(N):
        t = T[i]
        if t == "r":
            if i < K:
                memo[i] = "p" 
            else:
                if memo[i-K] == "p":
                    memo[i] = "."
                else:
                    memo[i] = "p"

        elif t == "s":
            if i < K:
                memo[i] = "r" 
            else:
                if memo[i-K] == "r":
                    memo[i] = "."
                else:
                    memo[i] = "r"
        else:
            if i < K:
                memo[i] = "s" 
            else:
                if memo[i-K] == "s":
                    memo[i] = "."
                else:
                    memo[i] = "s"
    score = 0

    for i in range(N):
        if memo[i] == "p":
            score+=P
        elif memo[i] == "s":
            score += S
        elif memo[i] == "r":
            score += R
        else:
            continue
    
    print(score)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    K = int(next(tokens))  
    R = int(next(tokens))  
    S = int(next(tokens))  
    P = int(next(tokens))  
    T = next(tokens)  
    solve(N, K, R, S, P, T)

if __name__ == '__main__':
    main()

Solution (Python):

import sys
INF = float("inf")


def solve(N: int, K: int, R: int, S: int, P: int, T: str):
    score = [R, S, P]

    ans = 0
    past = []
    for i, t in enumerate(T):
        if t == "r":
            cand = 2
        elif t == "s":
            cand = 0
        else:
            cand = 1
        if i - K >= 0 and past[i-K] == cand:
            ans += 0
            past.append(-1)
        else:
            ans += score[cand]
            past.append(cand)
    print(ans)
    

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    K = int(next(tokens))  
    R = int(next(tokens))  
    S = int(next(tokens))  
    P = int(next(tokens))  
    T = next(tokens)  
    solve(N, K, R, S, P, T)


if __name__ == '__main__':
    main()

Solution (Python):
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7



N, K = list(map(int, sys.stdin.buffer.readline().split()))
R, S, P = list(map(int, sys.stdin.buffer.readline().split()))
T = sys.stdin.buffer.readline().decode().rstrip()


def solve(T):
    N = len(T)
    if N == 0:
        return 0
    
    dp = [[0, 0, 0] for _ in range(N)]
    dp[0][0] = R if T[0] == 's' else 0
    dp[0][1] = S if T[0] == 'p' else 0
    dp[0][2] = P if T[0] == 'r' else 0
    for i, cpu in enumerate(T[1:], start=1):
        dp[i][0] = max(dp[i - 1][1], dp[i - 1][2]) + R * int(cpu == 's')
        dp[i][1] = max(dp[i - 1][0], dp[i - 1][2]) + S * int(cpu == 'p')
        dp[i][2] = max(dp[i - 1][0], dp[i - 1][1]) + P * int(cpu == 'r')
    return max(dp[-1])


ans = 0
for k in range(K):
    ans += solve(T[k::K])
print(ans)

Solution (Python):
def examA():
    S, T = LSI()
    ans = T+S
    print(ans)
    return

def examB():
    A, B, K = LI()
    if A>K:
        A -=K
        print(A,B)
        return
    if A+B>K:
        B -=(K-A)
        A = 0
        print(A,B)
        return
    A = 0; B = 0
    print(A,B)
    return

def examC():
    def is_prime(n):
        if n == 1: return False
        for k in range(2, int(math.sqrt(n)) + 1):
            if n % k == 0:
                return False
        return True
    X = I()
    while(True):
        if is_prime(X):
            ans = X
            break
        X +=1
    print(ans)
    return

def examD():
    N, K = LI()
    R, S, P = LI()
    T = SI()
    C = Counter(T)
    sumT = C["r"]*P + C["s"]*R + C["p"]*S

    ans = sumT
    d = defaultdict(bool)
    for i in range(K,N):
        if T[i]==T[i-K] and not d[i-K]:
            if T[i]=="r":ans -=P
            elif T[i]=="s":ans -=R
            else:ans -=S
            d[i] = True
    print(ans)
    return

def examE():
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,inf
mod = 10**9 + 7
inf = float('inf')

if __name__ == '__main__':
    examD()

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

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

ans = 0
dp = [0] * n
for i in range(k):
    ans += get_score(t[i])
    dp[i] = 1

for i in range(k, n):
    if t[i] == t[i-k]:
        if dp[i-k] == 0:
            dp[i] = 1
            ans += get_score(t[i])
        else:
            dp[i] = 0
    else:
        ans += get_score(t[i])
        dp[i] = 1

print(ans)

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

T = input()
used = [False] * N

score = 0
for i, c in enumerate(T):
    if i >= K:
        if c == T[i - K] and used[i - K]:
            pass
        else:
            if c == 'r':
                score += P
            elif c == 'p':
                score += S
            else:
                score += R
            used[i] = True
    else:
        if c == 'r':
            score += P
        elif c == 'p':
            score += S
        else:
            score += R
        used[i] = True

print(score)

Solution (Python):
N,K = map(int,input().split())
R,S,P = map(int,input().split())
T = input()
rsp = [[R,'r'],[S,'s'],[P,'p']]
rsp.sort(key=lambda x:x[0], reverse=True)
dics = {'r':'s','s':'p','p':'r'}
out = ['0' for i in range(N)]
tot = 0
for i in range(3):
    for j in range(N):
        if j < K:
            if T[j] == dics[rsp[i][1]]:
                out[j] = rsp[i][1]
                tot += rsp[i][0]
        elif out[j-K] != rsp[i][1] and T[j] == dics[rsp[i][1]]:
            out[j] = rsp[i][1]
            tot += rsp[i][0]
print(tot)

Solution (Python):
N, K = map(int, input().split())
r, s, p = map(int, input().split())
T = input()
T = [T[i] for i in range(N)]

ans = 0
point = {'r': p, 's': r, 'p': s}
for i in range(N):
    if i < K:
        ans += point[T[i]]
    else:
        if T[i] != T[i-K]:
            ans += point[T[i]]
        else:
            T[i] = 'o'
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):
    dp = [0]*3
    for j in range(i, n, k):
        nxt = [-float("inf")]*3
        nxt[0] = max(dp[1], dp[2])
        if t[j] == "s":
            nxt[0] += r
        nxt[1] = max(dp[0], dp[2])
        if t[j] == "p":
            nxt[1] += s
        nxt[2] = max(dp[1], dp[0])
        if t[j] == "r":
            nxt[2] += p
        dp = nxt
    ans += max(dp)
print(ans)

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

L = [0]*N
ans = 0
for i in range(N):
    if i < K:
        if T[i] == "r":
            L[i] = "p"
            ans += P
        elif T[i] == "s":
            L[i] = "r"
            ans += R
        else:
            L[i] = "s"
            ans += S
    else:
        if T[i] == "r" and L[i-K] != "p":
            ans += P
            L[i] = "p"
        if T[i] == "s" and L[i-K] != "r":
            ans += R
            L[i] = "r"
        if T[i] == "p" and L[i-K] != "s":
            ans += S
            L[i] = "s"
                
print(ans)

Solution (Python):
N,K = map(int,input().split())
rsp = list(map(int,input().split()))
T = list(input())
ans = 0
for i in range(K):
    ans += rsp["spr".index(T[i])]
for i in range(K,N):
    if T[i] != T[i-K]:
        ans += rsp["spr".index(T[i])]
    else:
        T[i] = "z"
print(ans)

Solution (Python):
def calc(l):
    n = len(l)
    dp = [[0]*3 for _ in range(n+1)]
    
    for i in range(n):
        if l[i]=='r':
            dp[i+1][0] = max(dp[i][1], dp[i][2])
            dp[i+1][1] = max(dp[i][0], dp[i][2])
            dp[i+1][2] = max(dp[i][0], dp[i][1])+P
        elif l[i]=='s':
            dp[i+1][0] = max(dp[i][1], dp[i][2])+R
            dp[i+1][1] = max(dp[i][0], dp[i][2])
            dp[i+1][2] = max(dp[i][0], dp[i][1])
        else:
            dp[i+1][0] = max(dp[i][1], dp[i][2])
            dp[i+1][1] = max(dp[i][0], dp[i][2])+S
            dp[i+1][2] = max(dp[i][0], dp[i][1])
    
    return max(dp[n])

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

for i in range(K):
    l = []
    j = i
    
    for j in range(i, N, K):
        l.append(T[j])
    
    ans += calc(l)

print(ans)

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

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


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, R, S, P, T):
    ans = 0
    s = []
    for i, t in enumerate(T):
        if t == 'r':
            if i - K >= 0 and s[i-K] == 'p':
                s.append('.')
            else:
                s.append('p')
                ans += P
        elif t == 's':
            if i - K >= 0 and s[i-K] == 'r':
                s.append('.')
            else:
                s.append('r')
                ans += R
        elif t == 'p':
            if i - K >= 0 and s[i-K] == 's':
                s.append('.')
            else:
                s.append('s')
                ans += S
    return ans


def main():
    N, K = read_int_n()
    R, S, P = read_int_n()
    T = read_str()
    print(slv(N, K, R, S, P, T))


if __name__ == '__main__':
    main()

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,k = LI()
    r,s,p = LI()
    t = S()
    dp = [[0]*3 for _ in range(k)]
    for i in range(n):
        c = t[i]
        b = -1
        cp = dp[i%k]
        np = cp[:]
        mp = max(cp)
        if c == "r":
            np[2] = max(max(cp[0], cp[1]) + p, cp[2])
            np[1] = np[0] = mp
        elif c == "s":
            np[0] = max(max(cp[2], cp[1]) + r, cp[0])
            np[1] = np[2] = mp
        else:
            np[1] = max(max(cp[2], cp[0]) + s, cp[1])
            np[2] = np[0] = mp

        dp[i%k] = np

    return sum(map(max, dp))


print(main())

Solution (Python):
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=input()
ss=[""]*k
ans=0
for i in range(n):ss[i%k]+=t[i]
for t in ss:
  m=len(t)
  dp=[[0,0,0]for _ in range(m)]
  
  if t[0]=="r":dp[0]=[0,0,p]
  elif t[0]=="s":dp[0]=[r,0,0]
  else:dp[0]=[0,s,0]
  for i in range(1,m):
    dp[i]=[max(dp[i-1][1],dp[i-1][2]),max(dp[i-1][0],dp[i-1][2]),max(dp[i-1][0],dp[i-1][1])]
    if t[i]=="r":
      dp[i][2]+=p
    if t[i]=="s":dp[i][0]+=r
    if t[i]=="p":dp[i][1]+=s
  ans+=max(dp[-1])
print(ans)

Solution (Python):

N,K = map(int,input().split())

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

T = input()

ans = 0
t = ""

for i in range(N):

    if T[i] == "r":

        if len(t) < K or (len(t) >= K and t[-K] != "P"):
            ans += P
            t += "P"
        else:
            t += "N"

    if T[i] == "s":

        if len(t) < K or (len(t) >= K and t[-K] != "R"):
            ans += R
            t += "R"
        else:
            t += "N"


    if T[i] == "p":

        if len(t) < K or (len(t) >= K and t[-K] != "S"):
            ans += S
            t += "S"
        else:
            t += "N"

print (ans)

Solution (Python):



n,k = map(int,input().split())
r,s,p = map(int,input().split())
t = list(input())
ans = 0
D = {"r":p, "s":r, "p":s}
for i in range(n):
    if i-k < 0 or t[i] != t[i-k]:
        ans += D[t[i]]
    else:
        t[i] = "n"
        
    
print(ans)

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

texts = []
for i in range(k):
    text = T[i::k]
    texts.append(text)

ans = 0
for text in texts:
    prev = ''
    for t in text:
        if t == prev:
            prev = ''
            continue

        else:
            prev = t
            ans += dict[t]

print(ans)

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, raw_input().split())
R, S, P = map(int, raw_input().split())
T = raw_input()

ans = 0
X = ["."]*N
for i in range(N):
  if T[i]=="r" and (i<K or X[i-K]!="p"):
    ans += P
    X[i] = "p"
  if T[i]=="p" and (i<K or X[i-K]!="s"):
    ans += S
    X[i] = "s"
  if T[i]=="s" and (i<K or X[i-K]!="r"):
    ans += R
    X[i] = "r"
print ans

Solution (Python):
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=input()
count=0
dp=[0]*n
for i in range(n):
    if i<k:
        if t[i]=='r':
            count+=p
        elif t[i]=='s':
            count+=r
        else:
            count+=s
        dp[i]=1
        continue
    if t[i]==t[i-k] and dp[i-k]==1:
        continue
    if t[i]=='r':
        count+=p
    elif t[i]=='s':
        count+=r
    else:
        count+=s
    dp[i]=1
print(count)

Solution (Python):




import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

n,k = [int(i) for i in readline().split()]
r,s,p = [int(i) for i in readline().split()]
t = input()

ans = 0

for i in range(k):
    tt = t[i::k]
    l = len(tt)
    dpr = dps = dpp = 0
    for i in tt:
        if i == "r":
            dpr,dps,dpp = max(dps,dpp),max(dpr,dpp),max(dps,dpr)+p
        if i == "s":
            dpr,dps,dpp = max(dps,dpp)+r,max(dpr,dpp),max(dps,dpr)
        if i == "p":
            dpr,dps,dpp = max(dps,dpp),max(dpr,dpp)+s,max(dps,dpr)

    ans += max(dpr,dps,dpp)


print(ans)

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
point = {"r": P, "s": R, "p": S}
T = input()


res = [0 for _ in range(N)]
for i, t in enumerate(T):
    if i - K < 0 or (i - K >= 0 and (res[i - K] == 0 or T[i - K] != T[i])):
        res[i] = point[t]

print(sum(res))

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
s = input()
d = {"r" : P, "s" : R, "p" : S}
dd = set()
r = 0
for i in range(N):
    r += d[s[i]]
    if i >= K:
        if i-K not in dd:
            if s[i-K] == s[i]:
                dd.add(i)
                r -= d[s[i]]
print(r)

Solution (Python):
N,K=[int(i) for i in input().split(" ")]
R,S,P=[int(i) for i in input().split(" ")]
T=input()


score=0
for i in range(K):
    hand=T[i::K]
    hand=hand.replace("pp","p")
    hand=hand.replace("rr","r")
    hand=hand.replace("ss","s")
    for h in hand:
        if h=="p":
            score+=S
        elif h=="r":
            score+=P
        else:
            score+=R
print(score)

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,hypot,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N,K=MI()
    R,S,P=MI()
    T=ST()
    te = [""]*N
    ans = 0
    win = {"r":"p","s":"r","p":"s"}
    for i,t in enumerate(T):
        if i>=K and win[t]==te[i-K]:
            continue
        else:
            if t=="r":
                ans += P
                te[i]="p"
            elif t=="s":
                ans += R
                te[i]="r"
            else:
                ans += S
                te[i]="s"
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
n, k = [int(i) for i in input().split()]
r, s, p = [int(i) for i in input().split()]
t = input()
a = {"r": p, "s": r, "p": s}
b = {"r": "p", "s": "r", "p": "s"}

ans = 0
u = ""
for i in t:
    if len(u)<k:
        ans += a[i]
        u+=b[i]
    elif u[-k] == b[i]:
        u+="1"
        ans += 0
    else:
        ans += a[i]
        u += b[i]

print(ans)

Solution (Python):
def main():
    N, K = [int(i) for i in input().split()]
    R, S, P = [int(i) for i in input().split()]
    T = input()
    hand = {"r":P, "s":R, "p":S}
    res = 0
    for i in range(K):
        
        last = ""
        j = i
        while j < N:
            
            aite = T[j]
            if aite != last:
                res += hand[aite]
                last = aite
            else:
                last=""
            j += K
    print(res)
main()

Solution (Python):
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
flag = [0]*N
ans = 0
for i in range(N):
    if i-K>=0 and T[i-K] == T[i] and flag[i-K]:
        continue
    if T[i] == 'r':
        ans+=P
    elif T[i] == 's':
        ans+=R
    else:
        ans+=S
    flag[i] = True
print(ans)