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

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

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

Submission status: Runtime Error

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

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

Submission status: Runtime Error

Solution code:
w, x= input().split(" ")
n = int(w)
k = int(x)

a, b, c = input().split(" ")
r = int(a)
s = int(b)
p = int(c)

t = str(input())
turn = []
score = 0

for i in range(1, n+1):
    turn.append('q')

for i in range(0, n):
    print(turn)
    print(turn[(i-k)%n], t[i])
    if t[i] == 'r':

        if turn[(i-k)%n] == 'p':
            turn[i] = 'r'
            continue
        score += p #7
        turn[i] = 'p'

    elif t[i] == 's':
        if turn[(i-k)%n] == 'r':
            turn[i] = 's'
            continue
        score += r #8
        turn[i] = 'r'

    elif t[i] == 'p':
        if turn[(i-k)%n] == 's':
            turn[i] = 'p'
            continue
        score += s #6
        turn[i] = 's'

print(score, turn)

Submission status: Runtime Error

Solution code:

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

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

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

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

    print(s)

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

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

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

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

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

    print(s)

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
N, K = [int(n) for n in input().split()]
R, S, P = [int(n) for n in input().split()]
w = {'r': ('p', P), 's': ('r', R), 'p': ('s', S)}
T = list(input())
p = []
ans = 0
for i, c in enumerate(T):
    if i<K:
        ans += w[c][1]
        p.append(w[c][0])
    else:
        if p.pop(0)!=w[c][0]:
            ans += w[c][1]
            p.append(w[c][0])
        else:
            if w[T[i+K]][0]==w[c][0]:
                p.append(w[T[i+K]][0])
            else:
                p.append(c)
print(ans)

Submission status: Runtime Error

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

dic = {"r":"p" , "s":"r" , "p":"s"}
ANS = []

for i in range(N):
    ANS.append(dic[T[i]])
    
ans = "".join(ANS)

VANISH = []
    
for i in range(N-K):
    if ans[i] == ans[i+K]:
        VANISH.append(ans[i])
        
if N - (2*K) > 0:
    for i in range(N - (2*K)):
        if ans[i] == ans[i+(2*K)]:
            VANISH.remove(ans[i])
            
vanish = "".join(VANISH)
        
point = ((ans.count("r")-vanish.count("r"))*R + (ans.count("s")-vanish.count("s"))*S + (ans.count("p")-vanish.count("p"))*P)

print(point)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = input()
ans = []
dp = [[None]*4 for _ in range(n+1)]

def solve(idx, score, move):
    if idx == n:
        return score

    # if dp[idx][0] is not None and dp[idx][1] is not None and dp[idx][2] is not None:
    #     return max(dp[idx][0], dp[idx][1], dp[idx][2])

    rock, sci, paper = 0, 0, 0

    if idx >= k:
        # print(idx, k)
        # print('move:', move)
        ng = move[idx-k]
        if ng == 'r':
            rock = -10**10
            if t[idx] == 'r':
                sci = solve(idx + 1, score, move + ['s'])
                paper = solve(idx + 1, score + p, move + ['p'])
            elif t[idx] == 's':
                sci = solve(idx + 1, score, move + ['s'])
                paper = solve(idx + 1, score, move + ['p'])
            elif t[idx] == 'p':
                sci = solve(idx + 1, score + s, move + ['s'])
                paper = solve(idx + 1, score, move + ['p'])
        elif ng == 's':
            sci = -10**10
            if t[idx] == 'r':
                rock = solve(idx + 1, score, move + ['r'])
                paper = solve(idx + 1, score + p, move + ['p'])
            elif t[idx] == 's':
                rock = solve(idx + 1, score + r, move + ['r'])
                paper = solve(idx + 1, score, move + ['p'])
            elif t[idx] == 'p':
                rock = solve(idx + 1, score, move + ['r'])
                paper = solve(idx + 1, score, move + ['p'])
        elif ng == 'p':
            paper = -10**10
            if t[idx] == 'r':
                rock = solve(idx + 1, score, move + ['r'])
                sci = solve(idx + 1, score, move + ['s'])
            elif t[idx] == 's':
                rock = solve(idx + 1, score + r, move + ['r'])
                sci = solve(idx + 1, score, move + ['s'])
            elif t[idx] == 'p':
                rock = solve(idx + 1, score, move + ['r'])
                sci = solve(idx + 1, score + s, move + ['s'])
    else:
        if t[idx] == 'r':
            rock = solve(idx+1, score, move + ['r'])
            sci = solve(idx+1, score, move + ['s'])
            paper = solve(idx+1, score + p, move + ['p'])
        elif t[idx] == 's':
            rock = solve(idx+1, score + r, move + ['r'])
            sci = solve(idx+1, score, move + ['s'])
            paper = solve(idx+1, score, move + ['p'])
        elif t[idx] == 'p':
            rock = solve(idx+1, score, move + ['r'])
            sci = solve(idx+1, score + s, move + ['s'])
            paper = solve(idx+1, score, move + ['p'])

    # if idx >= k:
    #     ng = move[idx-k]
    #     if ng == 'r':
    #         rock = -10**10
    #     elif ng == 'sr':
    #         sci = -10**10
    #     elif ng == 'p':
    #         paper = -10**10

    # dp[idx][0] = rock
    # dp[idx][1] = sci
    # dp[idx][2] = paper

    return max(rock, sci, paper)

print(solve(0, 0, []))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=str(input())
count=0
x=0
rsp=[]
while(x<=n-1):
  if(t[x]=="r"):
    if(rsp[x-k]==3):
      rsp.append(0)
    else:
      count+=p
      rsp.append(3)
  elif(t[x]=="s"):
    if(rsp[x-k]==1):
      rsp.append(0)
    else:
      count+=r
      rsp.append(1)
  elif(t[x]=="p"):
    if(rsp[x-k]==2):
      rsp.append(0)
    else:
      count+=s
      rsp.append(2)
  x+=1
print(count)

Submission status: Runtime Error

Solution code:
def towin(x,y):
    if x == "r" and y == "s":
        return True
    elif x == "s" and y == "p":
        return True
    elif x == "p" and y == "r":
        return True


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

n = int(n)
k = int(k)
r = int(r)
s = int(s)
p = int(p)
score = 0
_list = list(t)

_list_next = list()
for index, a in enumerate(_list):
    xx = ["r", "s", "p"]
    print(index-k+1)
    if index-k+1 > 0:
        print(score)
        xx.remove(_list_next[index-n+1])
        if towin(xx[0], a):
            if a == "r":
                score += p
            elif a == "s":
                score += r
            else:
                score += s
        elif towin(xx[1], a):
            if a == "r":
                score += p
            elif a == "s":
                score += r
            else:
                score += s
    else:
        if a == "r":
            _list_next.append("p")
            score += p
        elif a == "s":
            _list_next.append("r")
            score += r
        else:
            _list_next.append("s")
            score += s
print(score)

Submission status: Runtime Error

Solution code:
#############################
#
# じゃんけん説明
# r: グー
# s: チョキ
# p: パー
#
#############################
#
# 入力r -> 勝利時の グー の点数
# 入力s -> 勝利時の チョキ の点数
# 入力p -> 勝利時の パー の点数
#
#############################

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

MY_HAND = []
ANS = 0

def can_not_use_hand(after_k_hand):
  if after_k_hand == 'r':
    return 'p'
  if after_k_hand == 's':
    return 'r'
  if after_k_hand == 'p':
    return 's'

for battle_time in range(n):
  if battle_time < k:
    if t[battle_time] == "r":
      MY_HAND.append("p")
      ANS += p
    
    if t[battle_time] == "s":
      MY_HAND.append("r")
      ANS += r
    
    if t[battle_time] == "p":
      MY_HAND.append("s")
      ANS += s
  else:
    if t[battle_time] == "r": # 基本 -> [p]
      if MY_HAND[battle_time-k] == "p" and (battle_time+k) <= n: # [p] を前に使ってる -> [r, s, -]
        if can_not_use_hand(t[battle_time+k]) == 'r':
          MY_HAND.append("s")
          ANS += 0
        else:
          MY_HAND.append("r")
          ANS += 0
      else: # 基本通り
        MY_HAND.append("p")
        ANS += p

    if t[battle_time] == "s": # 基本 -> [r]
      if MY_HAND[battle_time-k] == "r" and (battle_time+k) <= n: # [r] を前に使ってる -> [-, s, p]
        if can_not_use_hand(t[battle_time+k]) == 's':
          MY_HAND.append("p")
          ANS += 0
        else:
          MY_HAND.append("s")
          ANS += 0
      else: # 基本通り
        MY_HAND.append("r")
        ANS += r
    
    if t[battle_time] == "p": # 基本 -> [s]
      if MY_HAND[battle_time-k] == "s" and (battle_time+k) <= n: # [s] を前に使ってる -> [r, -, p]
        if can_not_use_hand(t[battle_time+k]) == 'p':
          MY_HAND.append("r")
          ANS += 0
        else:
          MY_HAND.append("p")
          ANS += 0
      else: # 基本通り
        MY_HAND.append("s")
        ANS += s

print(ANS)

Submission status: Runtime Error

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

import sys
import math

debug = False

def log(text):
    if debug:
        print(text)

def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
#        for line in sys.stdin:
#            lines.append(line)
        lines.append(input())
        lines.append(input())
        lines.append(input())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]

    (n, k, r) = [int(e) for e in lines[0].split(" ")]
    (s, p) = [int(e) for e in lines[1].split(" ")]
    (t, ) = [int(e) for e in lines[2].split(" ")]

    return (n, k, r, s, p, t)

def solve(n, k, r, s, p, t):

    result = 0
    for i, c in enumerate(t):
        if c == 'r' and i - k >= 0 and t[i - k] != 'p':
            result = result + p
        elif c == 's' and i - k >= 0 and t[i - k] != 'r':
            result = result + r 
        elif c == 'p' and i - k >= 0 and t[i - k] != 's':
            result = result + s

    return result

def main():
    # 出力
    result = solve(*parse_input())
    if isinstance(result, list):
        for r in result:
            print("%s" % r)
    else:
        print("%s" % result)

if __name__ == '__main__':

    main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

index = defaultdict(list)

for i, t in enumerate(T):
    index[t].append(i)


len_r = len(index['r'])
len_s = len(index['s'])
len_p = len(index['p'])

tmp = 0
flag = True
for i in index['r']:    
    if tmp % K == 0 and flag == True:
        len_r -= 1
        flag = False
        tmp = i
        continue
    if tmp % K == 0 and flag == False:    
        flag = True
        tmp = i
        continue
    tmp += i -tmp

tmp = 0
flag = True
for j in index['s']:    
    if tmp % K == 0 and flag == True:
        len_s -= 1
        flag = False
        tmp = js
        continue
    if tmp % K == 0 and flag == False:    
        flag = True
        tmp = j
        continue
    tmp += j - tmp

tmp = 0
flag = True
for k in index['p']:    
    if tmp % K == 0 and flag == True:
        len_p -= 1
        flag = False
        tmp = k
        continue
    if tmp % K == 0 and flag == False:    
        flag = True
        tmp = k
        continue
    tmp += k-tmp

ans = P * len_r + R * len_s + S * len_p
print(ans)

Submission status: Runtime Error

Solution code:
#include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
#include <cstdlib>

typedef long long ll;
using namespace std;

int N, K;
int R, S, P;
string T;

int max(int a, int b)
{
	return (a > b) ? a : b;
}
int dpcalc(int begin)
{
	static int DP[100000 + 1][3];
	int pos = begin;

	for (int i = 0; i <= 100000; i++) {
		for (int j = 0; j < 3; j++) {
			DP[i][j] = 0;
		}
	}
	int n = 0;
	while (pos < N) {
		char t = T[pos];
		if (t == 'r') {
			DP[n + 1][0] = max(DP[n][1], DP[n][2]);
			DP[n + 1][1] = max(DP[n][0], DP[n][2]);
			DP[n + 1][2] = max(DP[n][1], DP[n][0]) + P;
		}
		if (t == 's') {
			DP[n + 1][0] = max(DP[n][1], DP[n][2]) + R;
			DP[n + 1][1] = max(DP[n][0], DP[n][2]);
			DP[n + 1][2] = max(DP[n][1], DP[n][0]);
		}
		if (t == 'p') {
			DP[n + 1][0] = max(DP[n][1], DP[n][2]);
			DP[n + 1][1] = max(DP[n][0], DP[n][2]) + S;
			DP[n + 1][2] = max(DP[n][1], DP[n][0]);
		}
		n++;
		pos += K;
	}
	return max(max(DP[n][0], DP[n][1]), DP[n][2]);
}

int main()
{

	cin >> N >> K;
	cin >> R >> S >> P;
	cin >> T;

	int ans = 0;
	for (int i = 0; i < K; i++) {
		ans += dpcalc(i);
	}
	cout << ans << endl;
}

Submission status: Runtime Error

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

dic = {"r":"p" , "s":"r" , "p":"s"}
ANS = []

for i in range(N):
    ANS.append(dic[T[i]])
    
ans = "".join(ANS)

VANISH = []
    
for i in range(N-K):
    if ans[i] == ans[i+K]:
        VANISH.append(ans[i])

print(VANISH)
        
if N - (2*K) > 0:
    for i in range(N - (2*K)):
        if ans[i] == ans[i+(2*K)]:
            VANISH.remove(ans[i])
            
print(VANISH)
            
vanish = "".join(VANISH)
        
point = ((ans.count("r")-vanish.count("r"))*R + (ans.count("s")-vanish.count("s"))*S + (ans.count("p")-vanish.count("p"))*P)

print(point)

Submission status: Runtime Error

Solution code:
n = int(input("Enter N: "))
k = int(input("Enter K: "))
r = int(input("Enter R: "))
s = int(input("Enter S: "))
p = int(input("Enter P: "))
t = input("Enter T: ")

total_score = 0
user_hand = []

def add_score(a):
    if a == 'r':
        user_hand.append('p')
        return p
    elif a == 's':
        user_hand.append('r')
        return r
    else:
        user_hand.append('s')
        return s

total_score = total_score + add_score(t[0])
t = t[1:]
for i in range(len(t)):
    if k > i:
        total_score = total_score + add_score(t[i])
        continue
    next_hand = 's'
    if t[i] == 'r':
        next_hand = 'p'
    elif t[i] == 's':
        next_hand = 'r'
    if next_hand != user_hand[i - k]:
        total_score = total_score + add_score(t[i])

print(total_score)

Submission status: Runtime Error

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

count=0
ban=[]
for i in range(k):
  if t[i]=='r':
    count+=p
  elif t[i]=='s':
    count+=r
  else:
    count+=s
  ban.append(t[i])

ban=ban[1:]
    
for i in range(k,n):
  if t[i]!=ban[0]:
    if t[i]=='r':
      count+=p
    elif t[i]=='s':
      count+=r
    else:
      count+=s
    ban.append(t[i])
  else:
    count+=0
    ban.append('x')
      
  if len(ban)>k:
    ban=ban[1:]
print(count)

Submission status: Runtime Error

Solution code:
import sys

nm = list(input().split(" "))
N = int(nm[0])
M = int(nm[1])
A = list(input().split(" "))
A.sort()
A.reverse()

ans = 0

start ,counter  = 0 , 0
flag1 = 0
flag2 = 0 # repete
flag3 = 0 # next step
for i in range(0,M):
    if flag1 == 0:
        ans += int(A[start]) + int(A[counter])
        counter += 1
        flag1 = 1
    elif flag2 == 0:
        ans += int(A[start]) + int(A[counter])
        flag2 = 1
    else:
        ans += int(A[start]) + int(A[counter])
        flag2 = 0
        if flag3 == 0:
            counter += 1
            if counter == N-1:
                flag3 = 1
        else:
            flag1 = 0
            flag3 = 0
            start += 1
            counter = start

print(ans)

Submission status: Runtime Error

Solution code:
#############################
#
# じゃんけん説明
# r: グー
# s: チョキ
# p: パー
#
#############################
#
# 入力r -> 勝利時の グー の点数
# 入力s -> 勝利時の チョキ の点数
# 入力p -> 勝利時の パー の点数
#
#############################

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

MY_HAND = []
ANS = 0

def can_not_use_hand(after_k_hand):
  if after_k_hand == 'r':
    return 'p'
  if after_k_hand == 's':
    return 'r'
  if after_k_hand == 'p':
    return 's'

for battle_time in range(n):
  if battle_time < k:
    if t[battle_time] == "r":
      MY_HAND.append("p")
      ANS += p
    
    if t[battle_time] == "s":
      MY_HAND.append("r")
      ANS += r
    
    if t[battle_time] == "p":
      MY_HAND.append("s")
      ANS += s
  else:
    if t[battle_time] == "r": # 基本 -> [p]
      if MY_HAND[battle_time-k] == "p": # [p] を前に使ってる -> [r, s, -]
        if can_not_use_hand(t[battle_time+k]) == 'r':
          MY_HAND.append("s")
          ANS += 0
        else:
          MY_HAND.append("r")
          ANS += 0
      else: # 基本通り
        MY_HAND.append("p")
        ANS += p

    if t[battle_time] == "s": # 基本 -> [r]
      if MY_HAND[battle_time-k] == "r": # [r] を前に使ってる -> [-, s, p]
        if can_not_use_hand(t[battle_time+k]) == 's':
          MY_HAND.append("p")
          ANS += 0
        else:
          MY_HAND.append("s")
          ANS += 0
      else: # 基本通り
        MY_HAND.append("r")
        ANS += r
    
    if t[battle_time] == "p": # 基本 -> [s]
      if MY_HAND[battle_time-k] == "s": # [s] を前に使ってる -> [r, -, p]
        if can_not_use_hand(t[battle_time+k]) == 'p':
          MY_HAND.append("r")
          ANS += 0
        else:
          MY_HAND.append("p")
          ANS += 0
      else: # 基本通り
        MY_HAND.append("s")
        ANS += s

print(ANS)

Submission status: Runtime Error

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

r = [0] * N
s = [0] * N
p = [0] * N

for i,j in enumerate(T):
    if j == "r":
        r[i] = 1
        continue
    if j == "s":
        s[i] = 1
        continue
    if j == "p":
        p[i] = 1

total = 0

chk = 0
for i in r:
    if i and chk == 0:
        total += scores["r"]
        chk = K
    else:
        chk = chk - 1 if chk > 0 else 0

chk = 0
for i in s:
    if i and chk == 0:
        total += scores["s"]
        chk = K
    else:
        chk = chk - 1 if chk > 0 else 0

chk = 0
for i in p:
    if i and chk == 0:
        total += scores["p"]
        chk = K
    else:
        chk = chl - 1 if chk > 0 else 0
    
print(total)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import random


def main():
    """Main function that will welcome the player to the game."""

    print("\tWelcome to Battle Sim! This is a turn based combat simulator where")
    print("\tthere can only be one winner.")

    print("\nHow to play.\n\nPlayers take turn to choose a move. Moves can either deal moderate damage")
    print("with a low range, deal high damage but over a wide")
    print("range, or they can heal. (Note: Moves can miss, including Heal!)")

    print("\nEach player starts with 100 health, and the first")
    print("player to reduce their opponent to 0 is the winner.")

    print("\nThat's it! Good luck")

    play_again = True

    # Set up the play again loop
    while play_again:
        winner = None
        player_health = 100
        computer_health = 100

        # determine whose turn it is
        turn = random.randint(1,2) # heads or tails
        if turn == 1:
            player_turn = True
            computer_turn = False
            print("\nPlayer will go first.")
        else:
            player_turn = False
            computer_turn = True
            print("\nComputer will go first.")


        print("\nPlayer health: ", player_health, "Computer health: ", computer_health)

        # set up the main game loop
        while (player_health != 0 or computer_health != 0):

            heal_up = False # determine if heal has been used by the player. Resets false each loop.
            miss = False # determine if the chosen move will miss.

            # create a dictionary of the possible moves and randomly select the damage it does when selected
            moves = {"Punch": random.randint(18, 25),
                     "Mega Punch": random.randint(10, 35),
                     "Heal": random.randint(20, 25)}

            if player_turn:
                print("\nPlease select a move:\n1. Punch (Deal damage between 18-25)\n2. Mega Punch (Deal damage between 10-35)\n3. Heal (Restore between 20-25 health)\n")

                player_move = input("> ").lower()

                move_miss = random.randint(1,5) # 20% of missing
                if move_miss == 1:
                    miss = True
                else:
                    miss = False

                if miss:
                    player_move = 0 # player misses and deals no damage
                    print("You missed!")
                else:
                    if player_move in ("1", "punch"):
                        player_move = moves["Punch"]
                        print("\nYou used Punch. It dealt ", player_move, " damage.")
                    elif player_move in ("2", "mega punch"):
                        player_move = moves["Mega Punch"]
                        print("\nYou used Mega Punch. It dealt ", player_move, " damage.")
                    elif player_move in ("3", "heal"):
                        heal_up = True # heal activated
                        player_move = moves["Heal"]
                        print("\nYou used Heal. It healed for ", player_move, " health.")
                    else:
                        print("\nThat is not a valid move. Please try again.")
                        continue

            else: # computer turn

                move_miss = random.randint(1,5)
                if move_miss == 1:
                    miss = True
                else:
                    miss = False

                if miss:
                    computer_move = 0 # the computer misses and deals no damage
                    print("The computer missed!")
                else:
                    if computer_health > 30: 
                        if player_health > 75:
                            computer_move = moves["Punch"]
                            print("\nThe computer used Punch. It dealt ", computer_move, " damage.")
                        elif player_health > 35 and player_health <= 75: # computer decides whether to go big or play it safe
                            imoves = ["Punch", "Mega Punch"]
                            imoves = random.choice(imoves)
                            computer_move = moves[imoves]
                            print("\nThe computer used ", imoves, ". It dealt ", computer_move, " damage.")
                        elif player_health <= 35:
                            computer_move = moves["Mega Punch"] # FINISH HIM!
                            print("\nThe computer used Mega Punch. It dealt ", computer_move, " damage.")                       
                    else: # if the computer has less than 30 health, there is a 50% chance they will heal
                        heal_or_fight = random.randint(1,2) 
                        if heal_or_fight == 1:
                            heal_up = True
                            computer_move = moves["Heal"]
                            print("\nThe computer used Heal. It healed for ", computer_move, " health.")
                        else:
                            if player_health > 75:
                                computer_move = moves["Punch"]
                                print("\nThe computer used Punch. It dealt ", computer_move, " damage.")
                            elif player_health > 35 and player_health <= 75:
                                imoves = ["Punch", "Mega Punch"]
                                imoves = random.choice(imoves)
                                computer_move = moves[imoves]
                                print("\nThe computer used ", imoves, ". It dealt ", computer_move, " damage.")
                            elif player_health <= 35:
                                computer_move = moves["Mega Punch"] # FINISH HIM!
                                print("\nThe computer used Mega Punch. It dealt ", computer_move, " damage.")

            if heal_up:
                if player_turn:
                    player_health += player_move
                    if player_health > 100:
                        player_health = 100 # cap max health at 100. No over healing!
                else:
                    computer_health += computer_move
                    if computer_health > 100:
                        computer_health = 100
            else:
                if player_turn:
                    computer_health -= player_move
                    if computer_health < 0:
                        computer_health = 0 # cap minimum health at 0
                        winner = "Player"
                        break
                else:
                    player_health -= computer_move
                    if player_health < 0:
                        player_health = 0
                        winner = "Computer"
                        break

            print("\nPlayer health: ", player_health, "Computer health: ", computer_health)

            # switch turns
            player_turn = not player_turn
            computer_turn = not computer_turn

        # once main game while loop breaks, determine winner and congratulate

        if winner == "Player":
            print("\nPlayer health: ", player_health, "Computer health: ", computer_health)
            print("\nCongratulations! You have won. You're an animal!!")
        else:
            print("\nPlayer health: ", player_health, "Computer health: ", computer_health)
            print("\nSorry, but your opponent wiped the floor with you. Better luck next time.")

        print("\nWould you like to play again?")

        answer = input("> ").lower()
        if answer not in ("yes", "y"):
            play_again = False

main()