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: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)
if sys.platform in (['ios','darwin','win32']):
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

def main():
	N, K = MAP()
	R, S, P = MAP()
	T = input().rstrip()

	Tokuten = [R, S, P]
	Te = ['r', 's', 'p']

	A = [-1] * N

	ans = 0
	for i in range(N):
		now = 0 if T[i]=='s' else 1 if T[i]=='p' else 2
		# print(Te[now])
		if i-K >= 0:
			past = 0 if T[i-K]=='s' else 1 if T[i-K]=='p' else 2
			# print(now, past, i)
			# 過去に出している手だったら、違う手を出す
			if past == now:
				if i-(2*K) >= 0:
					ppast = 0 if T[i-2*K]=='s' else 1 if T[i-2*K]=='p' else 2
					if ppast == past:
						A[i] = now
						ans += Tokuten[now]
					else:
						if i+K < N:
							feature = 0 if T[i+K]=='s' else 1 if T[i+K]=='p' else 2
							for j in range(3):
								if not j in [now, feature]:
									A[i] = j
						else:
							A[i] = (now+1)%3
				else:
					if i+K < N:
						feature = 0 if T[i+K]=='s' else 1 if T[i+K]=='p' else 2
						for j in range(3):
							if not j in [now, feature]:
								A[i] = j
					else:
						A[i] = (now+1)%3
			else:
				A[i] = now
				ans += Tokuten[now]
		else:
			A[i] = now
			ans += Tokuten[now]

	# print(A)
	for i in range(K, N):
		if A[i]==A[i-K]:
			f = A[i+K]
			for j in range(3):
				if not j in [A[i],f]:
					A[i] = j
	# print(A)

	ans = 0
	for i in range(N):
		te = A[i]
		if te==0 and T[i]=='s':
			ans += Tokuten[0]
		elif te==1 and T[i]=='p':
			ans += Tokuten[1]
		elif te==2 and T[i]=='r':
			ans += Tokuten[2]

	print(ans)
	
if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
#A text based RPG

#Import required modules
import jsonpickle
import os
import sys
import time
from random import randint
#main game

#Variables
go = True
IsShopLocked = False
IsDaggerEquipped = False
IsSwordEquipped = False
IsLeatherHideEquipped = False

SAVEGAME_FILENAME = 'savegame.json'

game_state = dict()

### Classes ###

class Human(object):
#Represents the human player in the game
    def __init__(self, name, health, strength, gold):
        self.name = name
        self.health = health
        self.strength = strength
        self.gold = gold

class AI(object):
#Represents the enemy player in the game
    def __init__(self, name, health, strength):
        self.name = name
        self.health = health
        self.strength = strength

class Item(object):
#represents any item in the game
    def __init__(self, name, hvalue, strvalue):
        self.name = name
        self.hvalue = hvalue
        self.strvalue = strvalue

###end classess###

###functions for loading, saving, and initializing the game###
def load_game():
    """Load game state from a predefined savegame location and return the
    game state contained in that savegame.
    """
    with open(SAVEGAME_FILENAME, 'r') as savegame:
        state = jsonpickle.decode(savegame.read())
    return state


def save_game():
    """Save the current game state to a savegame in a predefined location.
    """
    global game_state
    with open(SAVEGAME_FILENAME, 'w') as savegame:
        savegame.write(jsonpickle.encode(game_state))


def initialize_game():
    """If no savegame exists, initialize the game state with some
    default values.
    """
    global game_state
    player = Human('Fred', 100, 10, 1000)
    enemy = AI('Imp', 50, 20)

    state = dict()
    state['players'] = [player]
    state['npcs'] = [enemy]
    return state

###End functions for loading, saving, and initalizing the game###

###Main game functions###
#Function for the shop
def Shop():
    global game_state
    player = game_state['players'][0]
    dagger = Item('Dagger', 0, 5)
    sword = Item('Sword', 0, 10)
    leather_hide = Item('Leather Hide', 5, 0)
    if IsShopLocked == True:
        print("The shop is locked!\nPlease go back and continue your adventure!")
    else:
        print()
        print("Welcome to the Larkville shop! What would you like to buy?\n1. Weapons\n2. armor\n3. Go back")
        selection = int(input("Enter a value: "))

    if selection == 1:
        if player.gold >= 50:
            print("Weapons shop")
            print("1. Bronze Dagger: $20\n2. Bronze Sword: $50")
            wpnselection = int(input("Enter a value: "))

        if wpnselection == 1:
            global IsDaggerEquipped
            global IsSwordEquipped
            if IsDaggerEquipped == True or IsSwordEquipped == True:
                print("You already have this or another weapon equipped...")
                Game_Loop()
            else:
                dagger = Item('Dagger', 0, 5)
                IsDaggerEquipped = True
                player.strength += dagger.strvalue
                player.gold -= 20
                print("strength increased to: {}".format(player.strength))
                Game_Loop()

        elif wpnselection == 2:
            if IsDaggerEquipped == True or IsSwordEquipped == True:
                print("You already have this or another weapon equipped...")
                Game_Loop()
            else:
                sword = Item('Sword', 0, 10)
                IsSwordEquipped = True
                player.strength += sword.strvalue
                player.gold -= 50
                print("strength increased to: {}".format(player.strength))
                Game_Loop()

        elif wpnselection == 3:
            Game_Loop()

    elif selection == 2:
        if player.gold >= 20:
            print ("Armor Shop")
            print ("1. Leather hide\n2. Go back")
            armselection = int(input("enter a value: "))

        if armselection == 1:
            global IsLeatherHideEquipped
            if IsLeatherHideEquipped == True:
                print("You are already wearing armor!")
                Game_Loop()
            else:
                leather_hide = Item('Leather Hide', 5, 0)
                IsLeatherHideEquipped = True
                player.health += leather_hide.hvalue
                player.gold -= 20
                print("Health increased to: {}".format(player.health))
                Game_Loop()

        elif armselection == 2:
            Game_Loop()

    elif selection == 3:
        Game_Loop()

#Function for combat
def Combat():
    global game_state
    player = game_state['players'][0]
    enemy = game_state['npcs'][0]
    global go
    while go == True:
        dmg = randint (0, player.strength)
        edmg = randint (0, enemy.strength)
        enemy.health -= dmg

        if player.health <= 0:
            os.system('cls')
            print()
            print("You have been slain by the enemy {}...".format(enemy.name))
            go = False
            leave = input("press enter to exit")

        elif enemy.health <= 0:
            os.system('cls')
            print()
            print("You have slain the enemy {}!".format(enemy.name))
            go = False
            leave = input("press any key to exit")

        else:
            os.system('cls')
            with open("test.txt", "r") as in_file:
                text = in_file.read()
            print(text)
            player.health -= edmg
            print()
            print("You attack the enemy {} for {} damage!".format(enemy.name, dmg))
            print("The enemy has {} health left!".format(enemy.health))
            print()
            print("The enemy {} attacked you for {} damage!".format(enemy.name, edmg))
            print("You have {} health left!".format(player.health))
            time.sleep(3)

#The main game loop
def Game_Loop():

    global game_state

    while True:
        print()
        print("You are currently in your home town of Larkville!")
        print("What would you like to do?")
        print("1. Shop\n2. Begin/continue your adventure\n3. View player statistics\n4. save game")
        print()

        try:
            selection = int(input("Enter a value: "))
        except ValueError:
            print()
            print("You can only use the numbers 1, 2, or 3.")
            print()
            Game_Loop()
        if selection == 1:
            Shop()
        elif selection == 2:
            Combat()
        elif selection == 3:
            player = game_state['players'][0]            
            print()
            print("Your players stats:\nHealth: {}\nStrength: {}\nGold: {}".format(player.health, player.strength, player.gold))
            if IsDaggerEquipped == True:
                print("You have a dagger equipped")
            elif IsSwordEquipped == True:
                print ("You have a sword equipped")
            elif IsLeatherHideEquipped == True:
                print("You are wearing a leather hide")
        elif selection == 4:
            game_state = save_game()
        else:
            print()
            print("Oops! Not a valid input")
            print()

###End main game functions###

###The "main" function, not to be confused with anything to do with main above it###
def main():
    """Main function. Check if a savegame exists, and if so, load it. Otherwise
    initialize the game state with defaults. Finally, start the game.
    """
    global game_state

    if not os.path.isfile(SAVEGAME_FILENAME):
        game_state = initialize_game()
    else:
        game_state = load_game()
    Game_Loop()


if __name__ == '__main__':
    main()

###end main function###

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = list(input())
ro, si, pa = 0,0,0
rp, sp, pp = 0,0,0
for t in range(len(T)):
	if T[t] == 'r':
		pa += 1
		if (t - K >= 0 and T[t-K] == 'r') and (t+K>N or(t+K<=N and T[t+K] != 'r')):
			pp += 1
	if T[t] == 's':
		ro += 1
		if (t - K >= 0 and T[t-K] == 's') and (t+K>N or(t+K<=N and T[t+K] != 's')):
			rp += 1
	if T[t] == 'p':
		si += 1
		if (t - K >= 0 and T[t-K] == 'p') and (t+K>N or(t+K<=N and T[t+K] != 'p')):
			sp += 1
s_r = (ro-rp)*R
s_s = (si-sp)*S
s_p = (pa-pp)*P
print(s_r+s_s+s_p)

Submission status: Runtime Error

Solution code:
from random import randint
 
class Character:
  def __init__(self):
    self.name = ""
    self.health = 1
    self.health_max = 1
  def do_damage(self, enemy):
    damage = min(
        max(randint(0, self.health) - randint(0, enemy.health), 0),
        enemy.health)
    enemy.health = enemy.health - damage
    if damage == 0: print "%s evades %s's attack." % (enemy.name, self.name)
    else: print "%s hurts %s!" % (self.name, enemy.name)
    return enemy.health <= 0
 
class Enemy(Character):
  def __init__(self, player):
    Character.__init__(self)
    self.name = 'a goblin'
    self.health = randint(1, player.health)
 
class Player(Character):
  def __init__(self):
    Character.__init__(self)
    self.state = 'normal'
    self.health = 10
    self.health_max = 10
  def quit(self):
    print "%s can't find the way back home, and dies of starvation.\nR.I.P." % self.name
    self.health = 0
  def help(self): print Commands.keys()
  def status(self): print "%s's health: %d/%d" % (self.name, self.health, self.health_max)
  def tired(self):
    print "%s feels tired." % self.name
    self.health = max(1, self.health - 1)
  def rest(self):
    if self.state != 'normal': print "%s can't rest now!" % self.name; self.enemy_attacks()
    else:
      print "%s rests." % self.name
      if randint(0, 1):
        self.enemy = Enemy(self)
        print "%s is rudely awakened by %s!" % (self.name, self.enemy.name)
        self.state = 'fight'
        self.enemy_attacks()
      else:
        if self.health < self.health_max:
          self.health = self.health + 1
        else: print "%s slept too much." % self.name; self.health = self.health - 1
  def explore(self):
    if self.state != 'normal':
      print "%s is too busy right now!" % self.name
      self.enemy_attacks()
    else:
      print "%s explores a twisty passage." % self.name
      if randint(0, 1):
        self.enemy = Enemy(self)
        print "%s encounters %s!" % (self.name, self.enemy.name)
        self.state = 'fight'
      else:
        if randint(0, 1): self.tired()
  def flee(self):
    if self.state != 'fight': print "%s runs in circles for a while." % self.name; self.tired()
    else:
      if randint(1, self.health + 5) > randint(1, self.enemy.health):
        print "%s flees from %s." % (self.name, self.enemy.name)
        self.enemy = None
        self.state = 'normal'
      else: print "%s couldn't escape from %s!" % (self.name, self.enemy.name); self.enemy_attacks()
  def attack(self):
    if self.state != 'fight': print "%s swats the air, without notable results." % self.name; self.tired()
    else:
      if self.do_damage(self.enemy):
        print "%s executes %s!" % (self.name, self.enemy.name)
        self.enemy = None
        self.state = 'normal'
        if randint(0, self.health) < 10:
          self.health = self.health + 1
          self.health_max = self.health_max + 1
          print "%s feels stronger!" % self.name
      else: self.enemy_attacks()
  def enemy_attacks(self):
    if self.enemy.do_damage(self): print "%s was slaughtered by %s!!!\nR.I.P." %(self.name, self.enemy.name)
 
Commands = {
  'quit': Player.quit,
  'help': Player.help,
  'status': Player.status,
  'rest': Player.rest,
  'explore': Player.explore,
  'flee': Player.flee,
  'attack': Player.attack,
  }
 
p = Player()
p.name = raw_input("What is your character's name? ")
print "(type help to get a list of actions)\n"
print "%s enters a dark cave, searching for adventure." % p.name
 
while(p.health > 0):
  line = raw_input("> ")
  args = line.split()
  if len(args) > 0:
    commandFound = False
    for c in Commands.keys():
      if args[0] == c[:len(args[0])]:
        Commands[c](p)
        commandFound = True
        break
    if not commandFound:
      print "%s doesn't understand the suggestion." % p.name

Submission status: Runtime Error

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

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

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

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

result = [''] * n
result_num = 0
for j in range(n):
  if j >= k and result[j - k] == win_map[t[j]]:
    if j < k + 2 and t[j] == win_map[t[j + k]]:
      result[j] = lose_map[t[j]]
    else:
      result[j] = t[j]
  else:
    result[j] = win_map[t[j]]
    result_num += score[win_map[t[j]]]


print(result_num)

Submission status: Runtime Error

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

for i in reversed(range(N)):
    if i>N-K:
        if T[i]=='r':
            ans.append('p')
            cnt +=R
        elif T[i]=='p':
            ans.append('s')
            cnt +=S
        elif T[i]=='s':
            ans.append('r')
            cnt +=P
    elif i<=N-K:
        if T[i]=='r':
            if ans[N-K-i]=='p':
                if T[i-K]=='p':
                    ans.append('r')
                elif T[i-K]=='s':
                    ans.append('s')
                elif T[i-K]=='r':
                    ans.appned('r')
            else:
                ans.append('p')
                cnt +=P
        elif T[i]=='p':
            if ans[N-K-i]=='s':
                if T[i-K]=='s':
                    ans.append('p')
                elif T[i-K]=='r':
                    ans.append('r')
                elif T[i-K]=='p':
                    ans.appned('p')
            else:
                ans.append('s')
                cnt +=S
        elif T[i]=='s':
            if ans[N-K-i]=='r':
                if T[i-K]=='r':
                    ans.append('s')
                elif T[i-K]=='p':
                    ans.append('p')
                elif T[i-K]=='s':
                    ans.appned('s')
            else:
                ans.append('r')
                cnt +=R

print(cnt)

Submission status: Runtime Error

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 - 1:
        # グー
        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:
                    hands.append(list(set('rsp') - set([T[i+K], hands[i-K]]))[0])
        # チョキ
        elif T[i] == 's':
            if hands[i-K] != 'r':
                ans += R
                hands.append('r')
            else:
                if i + K <= N:
                    hands.append(list(set('rsp') - set([T[i+K], hands[i-K]]))[0])
        # パー
        else:
            if hands[i-K] != 's':
                ans += S
                hands.append('s')
            else:
                if i + K <= N:
                    hands.append(list(set('rsp') - set([T[i+K], hands[i-K]]))[0])
print(ans)

Submission status: Runtime Error

Solution code:
for i in range(n):
    if i<k:
        if t[i] =='r':
            ans+=p
        elif t[i] =='s':
            ans+=r
        else :
            ans+=s
    else:
        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]='a'
            continue
print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

################ DANGER ################
test = ""
#test = \
"""
5 2
8 7 6
rsrpr
ans 27
"""

"""
7 1
100 10 1
ssssppr
ans 211
"""

"""
30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr
ans 4996
"""
########################################
test = list(reversed(test.strip().splitlines()))
if test:
    def input2():
        return test.pop()
else:
    def input2():
        return input()
########################################  
        
n, k = map(int, input2().split())
r, s, p = map(int, input2().split())
t = list(input2())

rsp = {"r", "s", "p"}

for i in range(k, n):
    if t[i] == t[i-k]:
        t[i] = rsp - {t[i], t[i+1]}

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

print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
score = list(map(int,input().split()))
T = list(map(str,input()))
H = [0,1,2]
for n in range(len(T)):
    if T[n] == "r":
        T[n] = 0
    elif T[n] == "s":
        T[n] = 1
    else:
        T[n] = 2
 
X = []
for a in range(K):
    X.append(T[a::K])
 
sum = 0
for x in X:
    M = 0
    for first in range(3):
        #初手の点数を計算
        if (first + 1) % 3 == x[0]:
            first_s = score[first]
        else:
            first_s = 0
        #bit 全探索
        n = len(x)
        for i in range(2**(n-1)):
            print(i)
            temp = first_s
            last = first
            #print(last,end = "")
            for j in range(n-1):
                #print(last,end = "")
                h = H.copy()
                h.remove(last)  #前回の手を封印
 
                if ((i >> j)&1):
                    last = h[1]
                else:
                    last = h[0]
                
                if (last + 1) % 3 == x[j + 1]:
                    temp += score[last]
            #print("")
            #print(temp)
            M = max(temp,M)
    sum += M
print(sum)

Submission status: Runtime Error

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

t1 = t.replace("r","P")
t2 = t1.replace("s","R")
t3 = t2.replace("p","S")

# print(t3)
T = list(t3)
# print(T)
minus = 0
ls = ["R","S","P"]
for i in range(k,n):
    if i < n-k:
        tmp = T[i]
        before = T[i-k]
        after = T[i+k]
        if tmp == before:
            ls.remove(tmp)
            if tmp == after:
                T[i] = ls[0]
            else:
                ls.remove(after)
                T[i] = ls[0] 
                ls.append(after)
            ls.append(tmp)
            # if tmp == "R":
            #     minus += r
            # elif tmp == "S":
            #     minus += s
            # else:
            #     minus += p
            if T[i] == "R":
                minus += r
            elif T[i] == "S":
                minus += s
            elif T[i] == "P":
                minus += p
        else:
            pass
    elif i >= n-k:
        tmp = T[i]
        before = T[i-k]
        # after = T[i+k]
        if tmp == before:
            ls.remove(tmp)
            # if tmp == after:
            #     T[i] = ls[0]
            # else:
            #     ls.remove(after)
            #     T[i] = ls[0] 
            #     ls.append(after)
            tmp = ls[0]
            ls.append(tmp)
            # if tmp == "R":
            #     minus += r
            # elif tmp == "S":
            #     minus += s
            # else:
            #     minus += p
            if T[i] == "R":
                minus += r
            elif T[i] == "S":
                minus += s
            elif T[i] == "P":
                minus += p
        else:
            pass

# print(T)
p1 = r * T.count("R")
# print(p1)
p2 = s * T.count("S")
# print(p2)
p3 = p * T.count("P")
# print(p3)
# print(minus)

print(p1+p2+p3-minus)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys



def f(li: str, R, S, P):
    dp = [0,0,0]

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

    for i in range(1, len(li)):
        a = max(dp[1], dp[2])
        b = max(dp[0], dp[2])
        c = max(dp[0], dp[1])
        if li[i] == "r":
            c += P
        elif li[i] == "s":
            a += R
        else:
            b += S
        dp = [a, b, c]

    return max(dp)


def solve(N: int, K: int, R: int, S: int, P: int, T: str):
    ans = 0
    li_len = N // K + 1 if N % K != 0 else N // K

    for i in range(K):
        li = ""
        for j in range(li_len-1):
            li += T[i + j*K]
        if N > i + li_len*(K-1) + 1:
            li += T[i + (li_len-1)*K]

        ans += f(li, R, S, P)

    print(ans)




    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    R = int(next(tokens))  # type: int
    S = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    T = next(tokens)  # type: str
    solve(N, K, R, S, P, T)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
result = 0
str_list = list(t)
j_list = []
for i in range(n):
    if i >= k:
        dame = str_list[i-k]
    else:
        dame = ""
    if str_list[i] == "r":
        if dame != "p":
            result += p
            str_list[i] = "p"
        else:
            str_list[i] = "r"
    elif str_list[i] == "s":
        if dame != "r":
            result += r
            str_list[i] = "r"
        else:
            str_list[i] = "s"
    elif str_list[i] == "p":
        if dame != "s":
            result += s
            str_list[i] = "s"
        else:
            str_list[i] = "p"
print(result)

Submission status: Runtime Error

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

t1 = t.replace("r","P")
t2 = t1.replace("s","R")
t3 = t2.replace("p","S")

# print(t3)
T = list(t3)
# print(T)
minus = 0
ls = ["R","S","P"]
for i in range(k,n):
    if i < n-k:
        tmp = T[i]
        before = T[i-k]
        after = T[i+k]
        if tmp == before:
            ls.remove(tmp)
            if tmp == after:
                T[i] = ls[0]
            else:
                ls.remove(after)
                T[i] = ls[0] 
                ls.append(after)
            ls.append(tmp)
            # if tmp == "R":
            #     minus += r
            # elif tmp == "S":
            #     minus += s
            # else:
            #     minus += p
            if T[i] == "R":
                minus += r
            elif T[i] == "S":
                minus += s
            else:
                minus += p
        else:
            pass
    else:
        tmp = T[i]
        before = T[i-k]
        # after = T[i+k]
        if tmp == before:
            ls.remove(tmp)
            # if tmp == after:
            #     T[i] = ls[0]
            # else:
            #     ls.remove(after)
            #     T[i] = ls[0] 
            #     ls.append(after)
            tmp = ls[0]
            ls.append(tmp)
            # if tmp == "R":
            #     minus += r
            # elif tmp == "S":
            #     minus += s
            # else:
            #     minus += p
            if T[i] == "R":
                minus += r
            elif T[i] == "S":
                minus += s
            else:
                minus += p
        else:
            pass


# print(T)

p1 = r * T.count("R")
# print(p1)
p2 = s * T.count("S")
# print(p2)
p3 = p * T.count("P")
# print(p3)
# print(minus)

print(p1+p2+p3-minus)

Submission status: Runtime Error

Solution code:
#!python3

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

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

    s = 0
    for i in range(i, K):
        s += score[T[i]]

    for i in range(K, N):
        if T[i-K] == T[i]:
            continue
        s += score[T[i]]

    print(s)

if __name__ == "__main__":
    resolve()