Problem:


Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7



Sample input:
6 1
LRLRRL


Sample output:
3

Submission status: Wrong Answer

Solution code:
import sys
n, k = map(int, sys.stdin.readline().split())
S = sys.stdin.readline()

score = 0
for i in range(len(S)-1):
    if S[i]==S[i+1]:
        score+=1
#print(S)
idx = []
for i in range(n):
    if S[i] == 'R':
        idx.append(i)
idx.append(-10)

def change(S, s, e):
    S = S[0:s] + 'L'*len(S[s:e+1]) + S[e+1:]
    return S

s =-1
ten = []
for i in range(len(idx)-1):
    if s ==-1:
        s = idx[i]
    if idx[i]+1 != idx[i+1]:
        e = idx[i]
        S = change(S, s, e)
        if s ==0 or e ==len(S)-1:
            ten.append(1)
        else:
            ten.append(2)
        s =-1
ten = sorted(ten, reverse=True)
#print(score, ten)
print(score+ sum(ten[0:k]))

Submission status: Wrong Answer

Solution code:
import sys
n, k = map(int, sys.stdin.readline().split())
S = sys.stdin.readline()

score = 0
for i in range(len(S)-1):
    if S[i]==S[i+1]:
        score+=1
#print(S)
idx = []
for i in range(n):
    if S[i] == 'R':
        idx.append(i)
idx.append(-10)

def change(S, s, e):
    S = S[0:s] + 'L'*len(S[s:e+1]) + S[e+1:]
    return S

s =-1
ten = []
for i in range(len(idx)-1):
    if s ==-1:
        s = idx[i]
    if idx[i]+1 != idx[i+1]:
        e = idx[i]
        S = change(S, s, e)
        if s ==0 or e ==len(idx)-1:
            ten.append(1)
        else:
            ten.append(2)
        s =-1
ten = sorted(ten, reverse=True)
print(score+ sum(ten[0:k]))

Submission status: Wrong Answer

Solution code:
import sys
n, k = map(int, sys.stdin.readline().split())
S = sys.stdin.readline()

score = 0
for i in range(len(S)-1):
    if S[i]==S[i+1]:
        score+=1
#print(S)
idx = []
for i in range(n):
    if S[i] == 'R':
        idx.append(i)
idx.append(-1)

def change(S, s, e):
    S = S[0:s] + 'L'*len(S[s:e+1]) + S[e+1:]
    return S

s =-1
ten = []
for i in range(len(idx)-1):
    if s ==-1:
        s = idx[i]
    if idx[i]+1 != idx[i+1]:
        e = idx[i]
        S = change(S, s, e)
        if s ==0 or e ==len(idx)-1:
            ten.append(1)
        else:
            ten.append(2)
        s =-1
ten = sorted(ten, reverse=True)
print(score+ sum(ten[0:k]))

Submission status: Wrong Answer

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

left_RL = 0
middle_RL = 0
right_RL = 0
for i in range(N):
	if i == 0 and S[0] == "L":
		left_RL += 1
	elif i == N - 1 and S[N-1] == "R":
		right_RL += 1
	elif S[i:i+2] == "RL":
		middle_RL += 1

num_RL = left_RL + middle_RL + right_RL
if K >= num_RL - 1:
	print(N - 1)
else:
	print(N - 2*middle_RL - left_RL - right_RL + 2*K)

Submission status: Wrong Answer

Solution code:
N, K = [int(_) for _ in input().split()]
S = input()
now = ''
ans = 0
block = 0
for s in S:
    if now == s:
        ans += 1
    else:
        now = s
        block += 1
if K < block - 2:
    ans += 2 * K
elif K == block - 2:
    ans = N - 2
else:
    ans = N - 1
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(_) for _ in input().split()]
S = input()
now = ''
ans = 0
block = 1
for s in S:
    if now == s:
        ans += 1
    else:
        now = s
        block += 1
if K < block - 1:
    ans += 2 * K
elif K == block - 1:
    ans = N - 2
else:
    ans = N - 1
print(ans)

Submission status: Wrong Answer

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

if s[0] == "L":
    cnt = s.count("RL")
else:
    cnt = s.count("LR")
ans = s.count("LL")+s.count("RR")

if cnt >= k:
    ans += 2*k
else:
    ans += 2*cnt
    if (s[0] == "R" and s[n-1] == "L") or (s[0] == "L" and s[n-1] == "R"):
        ans +=1
print(ans)

Submission status: Wrong Answer

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

if s[0] == "L":
    cnt = s.count("RL")
else:
    cnt = s.count("LR")
ans = s.count("LL")+s.count("RR")

print(ans,cnt)

if cnt >= k:
    ans += 2*k
else:
    ans += 2*cnt
    if (s[0] == "R" and s[n-1] == "L") or (s[0] == "L" and s[n-1] == "R"):
        ans +=1
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
S = input()
a = 0
cnt1 = 0
cnt2 = 0
for i in range(len(S)-1):
  if S[i] != S[i+1]:
    if S[i]=="R":
      cnt1+=1
    else:
      cnt2+=1
  else:
    a+=1
b = cnt1//2+cnt2//2
if K > b:
  if cnt1%2 == 1 or cnt2%2 == 1:
    if cnt1%2 == 1 and cnt2%2 == 1 and K>b+1:
      print(a+b*2+2)
    else:
      print(a+b*2+1)
  else:
    print(a+b*2)
else:
  print(a+K*2)

Submission status: Wrong Answer

Solution code:
N,K=map(int, raw_input().split())
S=list(raw_input())

k=0
for i in range(1,N-1):
	if S[i]=="L" and S[i-1]==S[i+1]=="R":
		S[i]="R"
		k+=1
		if k==K:
			break

ans=0
prev=None
for i,s in enumerate(S):
	if i!=0 and prev==s:
		ans+=1
	prev=s

print ans

Submission status: Wrong Answer

Solution code:
n, k = [int(i) for i in input().split()]
S = list(input())

_l = 0
for _k in range(k):
    l = _l
    r = len(S) - 1
    for i in range(l + 1, len(S) - 1):
        if l == _l and S[i] != S[i - 1]:
            l = i
        if l > _l and S[i] == S[l] and S[i + 1] != S[l]:
            r = i
            break

    for i, s in enumerate(S[l:r+1]):
        S[r - i] = 'L' if s == 'R' else 'R'

    if _k > n / 2:
        break

    _l = l

score = 0
for i in range(len(S)):
    if i > 0 and S[i] == 'L' and S[i - 1] == 'L':
        score += 1
    elif i < len(S) - 1 and S[i] == 'R' and S[i + 1] == 'R':
        score += 1

print(score)

Submission status: Wrong Answer

Solution code:
n, k = [int(i) for i in input().split()]
S = list(input())

l = 0
for _k in range(k):
    r = len(S) - 1
    for i in range(l + 1, len(S) - 1):
        if l == 0 and S[i] != S[i - 1]:
            l = i
        if l > 0 and S[i] == S[l] and S[i + 1] != S[l]:
            r = i
            break

    buf = S[:]
    for i in range(r - l + 1):
        S[r - i] = 'L' if buf[l + i] == 'R' else 'R'

    if _k > n / 2:
        break

score = 0
for i in range(len(S)):
    if i > 0 and S[i] == 'L' and S[i - 1] == 'L':
        score += 1
    elif i < len(S) - 1 and S[i] == 'R' and S[i + 1] == 'R':
        score += 1

print(score)

Submission status: Wrong Answer

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

num_RL = 0
for i in range(N):
	if i == 0 and S[0] == "L":
		num_RL += 1
	elif i == N - 1 and S[N-1] == "R":
		num_RL += 1
	elif S[i:i+2] == "RL":
		num_RL += 1

if K >= num_RL - 1:
	print(N - 1)
else:
	print(N - 2*(num_RL - 1 - K))

Submission status: Wrong Answer

Solution code:
n, k = [int(i) for i in input().split()]
S = list(input())

for _ in range(k):
    l = -1
    r = len(S) - 1
    for i in range(1, len(S) - 1):
        if l < 0 and S[i] != S[i - 1]:
            l = i
        elif S[i] == S[l] and S[i + 1] != S[l]:
            r = i
            break

    buf = S[:]
    for i in range(r - l + 1):
        S[r - i] = 'L' if buf[l + i] == 'R' else 'R'

score = 0
for i in range(len(S)):
    if i > 0 and S[i] == 'L' and S[i - 1] == 'L':
        score += 1
    elif i < len(S) - 1 and S[i] == 'R' and S[i + 1] == 'R':
        score += 1

print(score)

Submission status: Wrong Answer

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

count = 0
for i in range(len(S)-1):
    if S[i]==S[i+1]:
        count += 1

ans = min(count + 2+K, N - 1)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = [int(x) for x in  input().split()]
S = list(input())
ans = [0]
a = []
for i in range(N-1):
  if S[i]!=S[i+1]:
  	ans.append(i)
ans.append(N-1)
#print(ans)
a = []
for i in range(1,len(ans)):
  a.append(ans[i]-ans[i-1])
a[0] +=1
ans2 = sum(a)-len(a)
#print(a)
print(ans2)
print(len(a)//2*2-1)
if len(a)!=1:
  ans2 = ans2 +(2*K)
print(min(ans2,len(S)-1))

Submission status: Wrong Answer

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

largest = 0
largest_left_index = -1

sum_list = list()

count = 0
for i in range(N):
    if S[i] == "L":
        if count <= 0:
            count = count - 1
        else:
            sum_list.append(count)
            count = -1
    elif S[i] == "R":
        if count >= 0:
            count = count + 1
        else:
            sum_list.append(-count)
            count = 1
else:
    sum_list.append(count) if count > 0 else sum_list.append(-count)

happines = 0
for i in range(len(sum_list)):
    happines = happines + sum_list[i] - 1

length = len(sum_list)

for i in range(K):
    if length > 2:
        happines = happines + 2
        length = length - 2
    elif length == 2:
        happines = happines + 1

print(happines)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = str(input())

count = 0
lr = 0
rl = 0
for i in range(N - 1):#start
  z = S[i]
  if S[i] == S[i + 1]:
    count += 1
  elif (S[i] == "L") and (S[i+1] == "R"):
    lr += 1
  elif (S[i] == "R") and (S[i+1] == "L"):
    rl += 1

if S[0] == "L":
  count -= 1
if S[-1] == "R":
  count -= 1
minlr = min(lr, rl)
maxlr = max(lr, rl) 
minK = min(K, minlr)
count += 2 * minK
  
print(min(count, N-1))

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = str(input())

count = 0
lr = 0
rl = 0
for i in range(N - 1):#start
  z = S[i]
  if S[i] == S[i + 1]:
    count += 1
  elif (S[i] == "L") and (S[i+1] == "R"):
    lr += 1
  elif (S[i] == "R") and (S[i+1] == "L"):
    rl += 1
 
minlr = min(lr, rl)
maxlr = max(lr, rl) 
if (maxlr == 1) and (minlr == 0):
  count += 1
  print(count) 
elif (maxlr == 1) and (minlr == 1):
  if ("LRL" in S) or ("RLR" in S):
    count += 1
    print(count)
  else:
    minK = min(K, minlr)
    count += 2 * minK
    print(count)
else:
  minK = min(K, minlr)
  count += 2 * minK
  print(count)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
S = str(input())

count = 0
lr = 0
rl = 0
for i in range(N - 1):#start
  z = S[i]
  if S[i] == S[i + 1]:
    count += 1
  elif (S[i] == "L") and (S[i+1] == "R"):
    lr += 1
  elif (S[i] == "R") and (S[i+1] == "L"):
    rl += 1
 
minlr = min(lr, rl)
maxlr = max(lr, rl) 
if (maxlr == 1) and (minlr == 0):
  count += 1
  print(count)
elif (maxlr == 2) and (minlr == 1):
  if ("RLRL" in S) or ("LRLR" in S):
    count += 1
    print(count)
  else:
    minK = min(K, minlr)
    count += 2 * minK
    print(count)    
else:
  minK = min(K, minlr)
  count += 2 * minK
  print(count)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
S = input()
bubun = []

tmp_leng = 1
tmp_hito = S[0]
for i in range(1,N):
    if S[i] == tmp_hito:
        tmp_leng += 1
    else:
        bubun.append(tmp_leng)
        tmp_leng = 1
    tmp_hito = S[i]
bubun.append(tmp_leng)
print(bubun)

for i in range(K):
    if len(bubun) < 3:
        bubun = [sum(bubun)]
        break
    tmp = []
    for j in range(len(bubun)-2):
        tmp.append(bubun[j] + bubun[j+1] + bubun[j+2])
    
    j = 0
    matome = tmp.index(max(tmp))
    print(matome)
    new_bubun = []
    while j < len(bubun):
        if j == matome:
            new_bubun.append(max(tmp))
            j += 3
        else:
            new_bubun.append(bubun[j])
            j += 1
    bubun = new_bubun
    print(bubun)

ans = 0
for _ in bubun:
    ans += _-1
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(200000)
input = sys.stdin.readline

N, M = map(int, input().split())
L = list(input().strip())

A = [0] * N
c = 1
index = 0
for i in range(N - 1):
    if L[i] == L[i + 1]:
        c += 1
    else:
        A[index] = c
        index += 1
        c = 1

A[index] = c

t = sum([v for v in A if v > 1])
if t == N:
    t -= 2

print(t + M)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(input())
count = 0
for i in range(N-1):
    if P[i] == P[i+1]:
        count += 1
time = 0
for i in range(1,N):
    if P[i] != P[i-1]:
        time += 1
if time == 1:
    print(count + 1)
elif time <= K:
    print(count + 2*time - 1)
else:
    print(count + 2*K)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(input())
count = 0
for i in range(N-1):
    if P[i] == P[i+1]:
        count += 1
time = 0
for i in range(1,N):
    if P[i] != P[i-1]:
        time += 1
if time == 1:
    print(count + 1)
elif time >= K:
    print(count + 2*time - 1)
else:
    print(count + 2*K)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(input())
count = 0
for i in range(N-1):
    if P[i] == P[i+1]:
        count += 1
time = 0
for i in range(1,N):
    if P[i] != P[i-1]:
        time += 1
if time == 1:
    print(count + 1)
else:
    print(count + 2*min(K,time-1/2))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""


N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    cnt2= 0
    if N == 1:
        return print(0)
    if N == 2:
        if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
            if 0 < cnt:
                return print(1)
            else:
                return print(0)
        
        if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
            return print(1)
    
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            if 0 < cnt:
                #print("reverse")
                if not n == N-1:
                    res += 2
                else:
                    res += 1
                cnt -= 1
                cnt2 += 1
        past = now
    if  cnt2 == 1 and res == N:
        return print(res-1)
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt and ("R" in S) :
            #print("reverse")
            res += 1
            cnt -= 1        
    if S[-1] == "R":
        res -= 1
        #print(N-1, ": edge BAD")
        
    return print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""


N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    cnt2= 0
    if N == 1:
        return print(0)
    if N == 2:
        if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
            if 0 < cnt:
                return print(1)
            else:
                return print(0)
        
        if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
            return print(1)
    
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            if 0 < cnt:
                #print("reverse")
                if not n == N-1:
                    res += 2
                else:
                    res += 1
                cnt -= 1
                cnt2 += 1
        past = now
    if  cnt2 == 1 and res == N:
        return print(res-1)
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt and 0 < cnt2 :
            #print("reverse")
            res += 1
            cnt -= 1        
    if S[-1] == "R":
        res -= 1
        #print(N-1, ": edge BAD")
        
    return print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect
import heapq

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    

"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)

"""


N, K = list(map(int, input().split()))
S = input()
    
def main():
    res = N
    past = S[0]
    cnt = K
    cnt2= 0
    if N == 1:
        return print(0)
    if N == 2:
        if (S[0] == "R" and S[1] == "L") or (S[0] == "L" and S[1] == "R"):
            if 0 < cnt:
                return print(1)
            else:
                return print(0)
        
        if (S[0] == "R" and S[1] == "R") or (S[0] == "L" and S[1] == "L"):
            return print(1)
    
    for n in range(1, N):
        now = S[n]
        #print(past, now, res)
        if past == "R" and now == "L":
            #print(n, ": BAD")
            res -= 2
            if 0 < cnt:
                #print("reverse")
                if not n == N-1:
                    res += 2
                else:
                    res += 1
                cnt -= 1
                cnt2 += 1
        past = now
    if  cnt2 == 1 and res == N:
        return print(res-1)
    #print("Reach edge: ", res)
    if S[0] == "L":
        #print(0, ": edge BAD")
        res -= 1
        if 0 < cnt:
            #print("reverse")
            res += 1
            cnt -= 1        
    if S[-1] == "R":
        res -= 1
        #print(N-1, ": edge BAD")
        
    return print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
S = list(input())

group = N-1
for i in range(1, N-1):
  if S[i-1] != S[i]:
    group -= 1
    
print(min(N-1, group+2*K))