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

Solution code:
nk=list(map(int,input().split()))
s=input()
L=[]
R=[]
lr="a"
for i in range(nk[0]):
    if lr=="L":
        if s[i]=="R":
            lr="R"
            R.append(1)
        else:
            L[-1]+=1
    elif lr=="R":
        if s[i]=="L":
            lr="L"
            L.append(1)
        else:
            R[-1]+=1
    else:
        lr=s[0]
        if lr=="L":
            L.append(1)
        else:
            R.append(1)
L.sort(reverse=True)
R.sort(reverse=True)
lsum=sum(L[:nk[1]])
rsum=sum(R[:nk[1]])
if len(L)<nk[1] or len(R)<nk[1]:
    print(n)
else:
    if lsum+sum(R)>rsum+sum(L):
        rmerge=sum(R[:nk[1]+1])+lsum
        R=R[nk[1]:]
        if R!=[]:
            R[0]=rmerge
        else:
            R=[rmerge]
        ans=sum(R)-len(R)
    else:
        lmerge=sum(L[:nk[1]+1])+rsum
        L=L[nk[1]:]
        if L!=[]:
            L[0]=lmerge
        else:
            L=[lmerge]
        ans=sum(L)-len(L)
    print(ans)

Submission status: Runtime Error

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

cnt = 0

i = 1
while i < len(s):
    print(i, s, cnt)
    if cnt == k:
        break

    if s[i] != s[i-1]:
        cnt += 1
        start = i
        target = s[i]

        while  i < len(s) and target == s[i]:
            if s[i] == 'R': s[i] = 'L'
            else: s[i] = 'R'

            i += 1   

        continue    

    i += 1

ans = 0
for i in range(1, len(s)):
    if s[i] == s[i-1]:
        ans += 1

print(ans)

Submission status: Runtime Error

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

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

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

Submission status: Runtime Error

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

ch = 0
ans = 0

if N != 0:
    for i in range(N):
        if i == 0:
            if S[i] != S[i+1]:
                ch += 1
            if S[i] == S[i+1] == 'R':
                ans += 1
        elif i == N-1:
            if S[i] == S[i-1] == 'L':
                ans += 1
        else:
            if S[i] != S[i+1]:
                ch += 1
            if S[i] == S[i+1] == 'R' or S[i] == S[i-1] == 'L':
                ans += 1

print(ans+min(K*2,ch))

Submission status: Runtime Error

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

ch = 0
ans = 0
for i in range(N):
    if i == 0:
        if S[i] != S[i+1]:
            ch += 1
        if S[i] == S[i+1] == 'R':
            ans += 1
    elif i == N-1:
        if S[i] == S[i-1] == 'L':
            ans += 1
    else:
        if S[i] != S[i+1]:
            ch += 1
        if S[i] == S[i+1] == 'R' or S[i] == S[i-1] == 'L':
            ans += 1

print(ans+min(K*2,ch))

Submission status: Runtime Error

Solution code:
N = int(input())

B = list(map(int, input().split()))
B.append(max(B[0], B[-1]))

ans = 0
for i in range(N):
    ans += min(B[i], B[i - 1])

print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
S = input()
ans = 0
for i in range(N):
    if S[i] == S[i+1]:
        ans += 1
ans += 2*K
if ans > N-1:
    ans = N-1
print(ans)

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()
	STR = input().rstrip()
	STR = [s for s in STR]

	ans = 0
	for num in range(2):
		S = STR[:]
		if not num%2: target = "L"
		else: target = "R"
		if not S.count(target): continue
		cand = []
		tmp = [-1,-1,-1,-1]
		for i, s in enumerate(S):
			# print(i, s)
			if s == target and tmp[0] == -1:
				tmp[0] = i
			elif (s != target or i == N-1) and tmp[0] != -1:
				tmp[1] = i if i != N-1 else i+1
				tmp[2] = i-tmp[0] if i != N-1 else i+1-tmp[0]
				if target=="L" and tmp[0]==0 or target=="R" and tmp[1]==N-1:
					tmp[3] = i-tmp[0]
				else:
					tmp[3] = i-tmp[0]+1
				cand.append(tmp)
				tmp = [-1,-1,-1,-1]

		cand.sort(key=lambda x:x[3], reverse=True)
		# print(cand)
		if not cand: continue
		
		s = "L" if target == "R" else "R"
		for i in range(K):
			fr, to, num, _ = cand[i]
			S[fr:to] = s*num
		# print(S)

		cnt = 0
		for i, s in enumerate(S):
			if i > 0 and s == "L" and S[i-1] == "L":
				cnt += 1
			elif i < N-1 and s == "R" and S[i+1] == "R":
				cnt += 1
		# print(cnt)
		ans = max(ans, cnt)

	print(ans)

if __name__ == '__main__':
	main()

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()
	STR = input().rstrip()
	STR = [s for s in STR]

	ans = 0
	for num in range(2):
		S = STR[:]
		if not num%2: target = "L"
		else: target = "R"
		cand = []
		tmp = [-1,-1,-1,-1]
		for i, s in enumerate(S):
			# print(i, s)
			if s == target and tmp[0] == -1:
				tmp[0] = i
			elif (s != target or i == N-1) and tmp[0] != -1:
				tmp[1] = i if i != N-1 else i+1
				tmp[2] = i-tmp[0] if i != N-1 else i+1-tmp[0]
				if target=="L" and tmp[0]==0 or target=="R" and tmp[1]==N-1:
					tmp[3] = i-tmp[0]
				else:
					tmp[3] = i-tmp[0]+1
				cand.append(tmp)
				tmp = [-1,-1,-1,-1]

		cand.sort(key=lambda x:x[3], reverse=True)
		# print(cand)
		
		s = "L" if target == "R" else "R"
		for i in range(K):
			fr, to, num, _ = cand[i]
			S[fr:to] = s*num
		# print(S)

		cnt = 0
		for i, s in enumerate(S):
			if i > 0 and s == "L" and S[i-1] == "L":
				cnt += 1
			elif i < N-1 and s == "R" and S[i+1] == "R":
				cnt += 1
		# print(cnt)
		ans = max(ans, cnt)

	print(ans)

if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = input()
l = s.count('L')
r = s.count('R')
now = 0
for i in range(len(s)-1):
  if s[i] == 'R' and s[i+1] == 'L':
    now += 1
print(min(now + K, min(l, r)))

Submission status: Runtime Error

Solution code:
n = int(input())
k = int(input())
s = input()
l = s.count('L')
r = s.count('R')
now = 0
for i in range(len(s)-1):
  if s[i] == 'R' and s[i+1] == 'L':
    now += 1
print(min(now + K, min(l, r)))

Submission status: Runtime Error

Solution code:
n = int(input())
k = int(input())
s = input()
l = s.count('L')
r = s.count('R')
now = 0
for i in range(len(s)-1):
  if s[i] == 'R' and s[i+1] == 'L':
    res += 1
print(min(now + K, min(l, r)))

Submission status: Runtime Error

Solution code:
n = int(input())
k = int(input())
s = input()
l = s.count('L')
r = s.count('R')
now = 0
for i in range(len(s)):
  if s[i] == 'R' and s[i+1] == 'L':
    res += 1
print(min(now + K, min(l, r)))

Submission status: Runtime Error

Solution code:
n = int(input())
b = list(map(int, input().split()))
if n == 2:
    print(b[0] * 2)
    exit()

a = []
b.append(b[-1])
for i in range(n):
    a.append(min(b[i - 1], b[i]))
print(sum(a))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
S=input()
O=[]
E=[]
flag=0
if n==1:
	print(0)
else:
	c=0
	for i in range(n-1):
		if S[i+1]==S[i]:
			c+=1
		else:
			if flag==0:
				O.append(c)
				c=0
				flag=1
			else:
				E.append(c)
				c=0
				flag=0
	if flag==0:
		O.append(c)
	else:
		E.append(c)
	Osum=sum(O)
	Esum=sum(E)		
	EC=len(E)
if flag==0:
	print(Osum+Esum+min(EC,k)*2)
else:
	print(Osum+Esum+min(2*EC-1,2*k))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = input()
segment = 0
now = '#'
ans = 0
for i in range(s):
    if i==now:
        segment+=1
        now = i
    else:
        ans+=1
for i in range(k):
    t = 0
    if segment > 2:
        t = 2
    elif segment == 2:
        t = 1
    segment, ans = segment-t, ans+t
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = input()
segment = 0
now = '#'
ans = 0
for i in range(s):
    if i=now:
        segment+=1
        now = i
    else:
        ans+=1
for i in range(k):
    t = 0
    if segment > 2:
        t = 2
    elif segment == 2:
        t = 1
    segment, ans = segment-t, ans+t
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
N,K = list(map(int,input().split()))
S = list(input())
S = deque(S)
i = 0
ans = 0
S_2 = [S.popleft()]
while len(S) > 0:
    if S[0] == S_2[-1]:
        ans += 1
        S.popleft()
    else:
        S_2.append(S.popleft())
cnt = 0

for i in range(1,len(S_2)-1):
    if S_2[i] != S_2[i-1] and S_2[i] != S_2[i+1]:
        ans += 2
        K -= 1
        S_2[i] = S_2[i-1]
        if K ==0:
            break
if K > 0:
    if len(S_2) == 1:
        print(ans)
    elif len(S_2) == 2 and S_2[0] != S_2[1]:
        print(ans + 1)
    else:
        if (S[0] != S[1] or S[-1] != S[-2]) and K == 1:
            print(ans + 1)
        elif K > 1 and (S[0] != S[1] and S[-1] != S[-2]):
            print(ans + 2)
        elif K > 1 and (S[0] != S[1] and S[-1] == S[-2]) or (S[0] == S[1] or S[-1] != S[-2]):
            print(ans + 1)
        else:
            print(ans)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
S = input()
s = S.split("L")
s = [i for i in s if i != '']
s.sort(reverse=True)
cnt = 0
for i in range(k):
    cnt += len(s[i])
    s.remove(s[i])
for i in s:
    if len(i) >= 2:
        cnt += len(i) - 1
r = S.split('R')
for i in r:
    if len(i) >= 2:
        cnt += len(i) - 1
    if len(i) == 1 and k > 0:
        cnt += 1
        k -= 1
print(cnt)

Submission status: Runtime Error

Solution code:
for i in range(N-1):
  if li[i] == li[i+1]:
    b += 1
  else:
    a += 1
for j in range(K):
  if a >= 2:
    a -= 2
    b += 2
  elif a == 1:
    a -= 1
    b += 1
  else:
    break
print(b)

Submission status: Runtime Error

Solution code:
def eval_(S):
    count = 0
    if(S[0]=="R" and S[1]=="R"):
        count += 1
    elif(S[len(S)-1]=="L" and S[len(S)-2]=="L"):
        count += 1
        
    for i in range(len(S)-2):
        num = i+1
        if(S[num]=="L" and S[num-1]=="L"):
            count += 1
        elif(S[num]=="R" and S[num+1]=="R"):
            count += 1
            
    return count

def flip(S,l,r):
    new_S = S.copy()
    for i in range(l-1,r-1):
        if(new_S[i]=="R"):
            new_S[i]="L"
        else:
            new_S[i]="R"
    return new_S
            
def dp(S,k):
    if(k==0):
        return eval_(S)
    else:
        #v1 = dp(S,0)
        #v2 = dp(S,k-1)
        val = 0
        for l in range(len(S)-1):
            for r in range(len(S)):
                if(l<=r):
                    new_S = flip(S,l,r)
                    val = max([val,dp(new_S,k-1)])
        return val
N,K = input().split()
N,K = int(N),int(K)
S = list(input())
print(dp(S,K))

Submission status: Runtime Error

Solution code:

N, K = [int(item) for item in input().split()]
S = [item for item in input()]

def compress(arr):
    """圧縮して消えた人はhappy"""
    cnt_h = 0
    new_arr = []
    comp_arr = ['L']

    #最初は先頭をLにする　この回転はノーカン
    if arr[0] == 'R':
        for item in arr:
            if item == 'L':
                new_arr.append('R')
            else:
                new_arr.append('L')

            prev_item = item
    else:
        new_arr = arr
    # 圧縮操作と圧縮されたかずを数える

    for i in range(1, N):
        if new_arr[i - 1] == new_arr[i]:
            cnt_h += 1
        else:
            comp_arr.append(new_arr[i])

    return [comp_arr, cnt_h] 


def execute(arr, cnt_h, K):
    # 境界を全て反転するために必要な操作回数
    max_rotation = len(arr)//2
    # 全てLになるか反転回数がKに到達するかで終了
    if max_rotation <= K:
        cnt += len(arr) - 1
    else:
            cnt_h += 2*K

    return cnt_h

arr, cnt_h = compress(S)
print(execute(arr, cnt_h, K))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = list(map(str, input()))
def change(x):
ans = 0
x = k
j = 1
w = n-2
while j<=w and x > 0:
    if s[j] != s[j-1]and s[w] != s[w+1]:
      if j==w:
        ans += 1
      else:
        ans += 2
      x -= 1
    elif s[j] == s[j-1]:
      j += 1
      ans += 1
    elif s[w] == s[w+1]:
      w -= 1
      ans += 1
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = list(map(str, input()))
a = 1
b = []
for i in range(1,n):
  if s[i] == s[i-1]:
    a += 1
  else:
    b.append(a)
    a = 1
c = [b[i] + b[i+1] + b[i+2] for i in range(len(b)-2)]
print(max(c))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = input()
pre = 0
sepS = []
happyCount = 0
RLcount = 0
for i in range(1, n):
    if s[i] == s[i - 1]:
        happyCount += 1
    if s[i] == 'L' and s[i - 1] == 'R':
        RLcount += 1
#print("now HP =>{}".format(happyCount))
happyCount += min(k, RLcount) * 2
if k > RLcount:
    happyCount += 1
print(min(n - 1, happyCount)

Submission status: Runtime Error

Solution code:
from operator import itemgetter

n, k = map(int, input().split())
s = input()
a = []
count = 1
for i in range(n - 1):
    if s[i] != s[i + 1]:
        a.append(count)
        count = 1
    else:
        count += 1
a.append(count)
ans = 0
for i in a:
    ans += i - 1
b = []
for i in range(len(a)):
    if i == 0:
        b.append((a[i] + a[i + 1], a[i], 2))
    elif i == len(a) - 1:
        b.append((a[i - 1] + a[i], a[i], 2))
    else:
        b.append((a[i - 1] + a[i] + a[i + 1], a[i], 3))
b = sorted(b, key=itemgetter(1))
b = sorted(b, reverse=True, key=itemgetter(0))
if k < len(b):
    for i in range(k):
        if b[i][2] == 3:
            ans += 2
        else:
            ans += 1
    print(ans)
else:
    print(n - 1)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = input()
a = []
count = 1
for i in range(n - 1):
    if s[i] != s[i + 1]:
        a.append(count)
        count = 1
    else:
        count += 1
a.append(count)
b = []
for i in range(len(a)):
    if i == 0:
        b.append(a[i] + a[i + 1])
    elif i == len(a) - 1:
        b.append(a[i - 1] + a[i])
    else:
        b.append(a[i - 1] + a[i] + a[i + 1])
b = sorted(b, reverse=True)
ans = 0
for i in range(k):
    ans += b[i] - 1
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
lr = list(input())
j = 0
counts = [0]
for i in range(n):
    if lr[j] == lr[i]:
        counts[-1] += 1
    else:
        j = i
        counts.append(1)

for _ in range(k):
    if len(counts)>=3:
        counts[0] += counts[1]+counts[2]
        del counts[1:3]
    else:
        counts[0] += counts[1]
        del counts[1]

count = sum(counts) - len(counts)
print(count)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

input = sys.stdin.readline

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

sq = deque(S)
lst=[]
j=0

for i in range(K):
    j=0
    sq_1st = sq.popleft()
    sq_2nd = sq_1st
    lst.append(sq_1st)

    while sq:
        sq_3rd = sq.popleft()
        if sq_2nd!=sq_3rd:
            j+=1
            sq_2nd=sq_3rd
            if j==2:
                sq.appendleft(sq_3rd)
                break
        lst.append(sq_1st)

lst+=list(sq)            
  
  

def eval(N,S):
    total=0
    for i in range(1,N):
        if S[i]==S[i-1]:total+=1
    return total
  
print(eval(N,lst))

Submission status: Runtime Error

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

count = 0
temp = S[1]

for i in range(0, len(S)-1):
    if S[i] == S[i+1]:
        count += 1
        
print( min(len(S)-1, count + 2*K) )

Submission status: Runtime Error

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

hikkuri = 0

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

shiawase = len(S) - hikkuri - 1

for i in range(K):
    if hikkuri >= 2:
        shiawase += 2
        hikkuri -= 2
    elif hikkuri == 1:
        shiawase += 1
        break

print(shiawase)N, K = map(int, input().split())
S = list(input())

hikkuri = 0

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

shiawase = len(S) - hikkuri - 1

for i in range(K):
    if hikkuri >= 2:
        shiawase += 2
        hikkuri -= 2
    elif hikkuri == 1:
        shiawase += 1
        break

print(shiawase)

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline

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

def eval(N,S):
    total=0
    for i in range(1,N):
        if S[i]==S[i-1]:total+=1
    return total

start_num=1
  
for k in range(K):
    if S==['R']*N or S==['L']*N:break
    j=[]
    for i in range(start_num, N):
        if S[i-1]!=S[i]:
            j.append(i)
            if len(j)==2:break
    if len(j)==1:j.append(N)
    if S[j[0]]=='R':
        S[j[0]:j[1]]=['L']*(j[1]-j[0])
    else:S[j[0]:j[1]]=['R']*(j[1]-j[0])
    start_num=j[1]+1
print(eval(N,S))

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline

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

def eval(N,S):
    total=0
    for i in range(1,N):
        if S[i]==S[i-1]:total+=1
    return total

start_num=1
  
for k in range(K):
    if S==['R']*N or S==['L']*N:break
    j=[]
    start_num=j[1]+1
    for i in range(start_num, N):
        if S[i-1]!=S[i]:
            j.append(i)
            if len(j)==2:break
    if len(j)==1:j.append(N)
    if S[j[0]]=='R':
        S[j[0]:j[1]]=['L']*(j[1]-j[0])
    else:S[j[0]:j[1]]=['R']*(j[1]-j[0])
print(eval(N,S))

Submission status: Runtime Error

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

def eval(N,S):
    total=0
    for i in range(1,N):
        if S[i]==S[i-1]:total+=1
    return total

for k in range(K):
    j=[]
    for i in range(1, N):
        if S[i-1]!=S[i]:
            j.append(i)
            if len(j)==2:break
    if len(j)==1:j.append(N)
    if S[j[0]]=='R':
        S[j[0]:j[1]]=['L']*(j[1]-j[0])
    else:S[j[0]:j[1]]=['R']*(j[1]-j[0])
    print(S)  
print(eval(N,S))

Submission status: Runtime Error

Solution code:

#L,Rの境界の数だけで処理を済ませる
#⇒いちいち書いてあるとおりに実装しない。

#内側の不幸な人を(RLの人)を消せば幸福な人が2人増える (全部Rに変えていくイメージ)
# ⇒着目するのは RL でも LR　でもどっちでもいい。
#  LRに注目する場合はこのあとのコードのRとLに関連する部分が逆になるだけ
#端っこなら１人増える
#幸福な人の最大値は N - 1

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

#端以外の人のせいで不幸な人の数
count = 0
#端の人のせいで不幸な人の数
edge_count = 0

#端のせいで不幸な人
if S[0] == 'L':
    edge_count += 1
if S[N-1] == 'R':
    edge_count += 1 

#端以外のせいで不幸になっている人の数を数える (RLを探す)
for i in range(N):
    if S[i] == 'R':
        if S[i+1] == 'L':
            count += 1

#最初の時点で幸せになれる人の数
happy = N  - (count*2 + edge_count)

#操作回数KがRLの数より小さい
if count >= K:
    print(min(N-1, K * 2 + happy  ))
#操作回数K がRLの数より大きい
else:
    print(min(N-1, K * 2 + happy + (min(edge_count,K - count) )))

Submission status: Runtime Error

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

cnt = 0
for i in range(n-1):
    if s[i] != s[i+1]:
        cnt += 1
ans = min(count+2*k, n-1)
print(ans)

Submission status: Runtime Error

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

cnt = 0
for i in range(n):
    if s[i] != s[i+1]:
        cnt += 1
ans = min(count+2*k, n-1)
print(ans)

Submission status: Runtime Error

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

cnt = 0
for i in range(n):
    if s[i] != s[i+1]:
        cnt += 1
ans = min(count+2*k, n-1)

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
L = input()
count=0
for i in range(N-1):
  if L[i]==L[i+1]:
    count += 1

print(min(count+2*L, N-1))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = input()
t = 0
for i in range(n - 1):
    if s[i] == s[i + 1]:
        t += 1
print(min([n - 1, h + 2 * k]))

Submission status: Runtime Error

Solution code:
from fractions import gcd


a, b, c, d = map(int, input().split())
lcm = int(c * d / gcd(c, d))
A = a - 1
l_cd = A - A // c - A // d + A // lcm
r_cd = b - b // c - b // d + b // lcm
print(r_cd - l_cd)

Submission status: Runtime Error

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

p = 0
while K > 0 and p < len(S):
	now = S[p]
	p += 1
	if p >= len(S):
		break
	while now == S[p]:
		p += 1
		if p >= len(S):
			break

	q = p + 1
	if q >= len(S):
		if S[p] == "R":
			S[p] = "L"
		else:
			S[p] = "R"
		break
	while S[p] == S[q]:
		q += 1
		if q >= len(S):
			break
	while p < q:
		if S[p] == "R":
			S[p] = "L"
		else:
			S[p] = "R"
		p += 1
		if p >= len(S):
			break
	K -= 1

ret = 0;
for x in range(len(S)-1):
	if S[x] == S[x + 1]:
		ret += 1
print(ret)

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc140/tasks/abc140_d

n, k = map(int, input().split())
str_n = input()
changed_str = [str_n]
first = str_n[0]
last = ""
if first == "R":
    last = "L"
else:
    last = "R"

for count in range(k): 
    new_line = changed_str[count]
    next_last = new_line.find(last)
    next_first = new_line.find(first, next_last)
    next_line = new_line[0:next_last]
    if next_first != -1:
        next_line += new_line[next_last:next_first].replace(last, first) + new_line[next_first:]
    else:
        next_line += new_line[next_last:].replace(last, first)
    changed_str.append(next_line)

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

print(count)

Submission status: Runtime Error

Solution code:
import sys


def dif(list):
    d = []
    for i in range(len(list)-1):
        d.append(list[i+1]-list[i])

    return d


def find_LR(list):
    ind = []
    for i in range(len(list)-1):
        if list[i:i+2] == "LR" or list[i:i+2] == "RL":
            ind.append(i)

    return ind


def rev_LR(l, min_i, max_i):
    if l[min_i] == "L":
        ls = list(l)
        for i in range(min_i, max_i):
            ls[i] = "R"
    else:
        ls = list(l)
        for i in range(min_i, max_i):
            ls[i] = "L"

    ll = "".join(ls)
    return ll


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

    return hp


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

for i in range(K):
    ind = find_LR(S)
    if len(ind) == 1:
        print(len(S)-1)
        sys.exit()
    d = dif(ind)
    qi = d.index(max(d))
    S = rev_LR(S, ind[qi]+1, ind[qi+1]+1)

print(cnt_happy(S))

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 5)

# L: True, R: False

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

ar = list(map(lambda v: v == 'L', list(S)))

def reorder(ar, l, r):
  l -= 1
  r -= 1

  ret = []
  ret.extend(ar[:l])
  ret.extend(reversed(list(map(lambda v: not v, ar[l:r + 1]))))
  ret.extend(ar[r + 1:])

  return ret

def evaluate(ar):
  happy = list(filter(lambda w: w, [v * ar[i - 1] for i, v in enumerate(ar[1:])]))

  return len(happy)

def try_once(ar, k, l = None, r = None):
  if k < 0:
    return 0
  
  res = [0]

  if l is not None:
    ar = reorder(ar, l, r)
    res.append(evaluate(ar))

  N = len(ar) + 1

  for l1 in range(1, N):
    for r1 in range(l1, N):
      res_recur = try_once(ar, k - 1, l1, r1)
      res.append(res_recur)

  return max(res)

res = try_once(ar, K, None, None)

print(res)

Submission status: Runtime Error

Solution code:
n, k=map(int, input().split())
s=input()
cnt=0
maxnum=len(s)-1
for i in range(n):
  if i==0:
    if s[i]=='L' and s[i+1]=='L':
      cnt +=1
  if i==n-1:
    if s[i]=='R' and s[i-1]=='R':
      cnt+=1
  else:
    if s[i] == 'L' and s[i+1] == 'L':
      cnt+=1
    if s[i] == 'R' and s[i+1] == 'R':
      cnt+=1

print(min(maxnum,cnt+k*2))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
S = input()
S0 = S[0]
SL = S[-1]
if N == 1:
    print(0)
    sys.exit(0)
else:
    cnt = S.count('RL')
    answer = 0
    if S0 == 'L' and SL == 'L':
        answer = N - 1
        answer -= cnt*2
        answer += K*2
        answer = answer if answer < N-1 else N-1
    if S0 == 'L' and SL == 'R':
        answer = N - 1
        answer -= cnt*2+1
        answer += K*2
        answer = answer if answer < N-1 else N-1
    if S0 == 'R' and SL == 'L':
        answer = N - 1
        answer -= cnt*2-1
        answer += K*2
        answer = answer if answer < N-1 else N-1
    if S0 == 'R' and SL == 'R':
        answer = N - 1
        answer -= cnt*2
        answer += K*2
        answer = answer if answer < N-1 else N-1
        
    print(answer)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define ALL(a) a.begin(), a.end()
ll dx[4] = { 0, 1, 0, -1 };
ll dy[4] = { 1, 0, -1, 0 };
const ll INF = 1e14;
const ll MOD = 1e9 + 7;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int N, K;
    cin >> N >> K;
    string S;
    cin >> S;
    int cnt = 0;
    for (int i = 1; i < N; i++) {
        if (S[i - 1] == S[i]) {
            cnt++;
        }
    }
    int ans = min(cnt + 2 * K, N - 1);
    cout << ans << endl;
    return 0;
}

Submission status: Runtime Error

Solution code:
def generate_block(s):
    table = []
    j = 0
    for i in range(len(s)-1):
        if s[i] != s[i+1]:
            table.append(s[j:i+1])
            j = i + 1
    return table

def happy(s):
    count = 0
    ll = len(s)
    for i in range(ll):
        if i != ll-1 and s[i] == 'R' and s[i+1] == 'R': count += 1
        if i != 0 and s[i] == 'L' and s[i-1] == 'L': count += 1
    return count

n, k = map(int, input().split())
s = input() + '.'
x = 0
table = generate_block(s)[::-1]
while k > 0:
    pos = 2 * x + 1
    if pos > len(table): break
    if 'L' in table[pos]: table[pos] = table[pos].replace('L', 'R')
    else: table[pos] = table[pos].replace('R', 'L')
    k -= 1
    x += 1
print(happy(''.join(table)))

Submission status: Runtime Error

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


def counthappy(s):
    happy = 0
    for i in range(0, len(s)):
        if i != 0 and s[i] == 'L':
            if s[i - 1] == 'L':
                happy += 1
        elif i != len(s) - 1 and s[i] == 'R':
            if s[i + 1] == 'R':
                happy += 1
    return happy


def replace(s, k_):
    for l in range(0, N - 1):
        for r in range(l + 1, N):
            part_l = s[0:l]
            part = s[l:r+1]
            part_r = s[r+1:N][::-1]

            part = part.replace('L', '-')
            part = part.replace('R', 'L')
            part = part.replace('-', 'R')
            s_ = part_l + part + part_r

            if k_ < K:
                replace(s_, k_ + 1)

            happy = counthappy(s_)
            global answer
            if answer < happy:
                answer = happy


answer = counthappy(S)
replace(S, 1)

print(answer)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
 
import numpy as np

N, K = map(int, input().split())
S = np.array(list(input()), dtype='U1')

S_slide = S[1:]
S_2 = S[:-1]

happiness = np.count_nonzero(S_slide == S_2)
happiness += 2*K

happiness = min(happiness, N-1)

print(happiness)

Submission status: Runtime Error

Solution code:
N, K = list(map(int, input().split()))
S = list(map(int, input().split()))
 
happy = 0
for i in range(N-1):
  if S[i] == S[i+1]:
    happy += 1
print(min([N-1, happy + 2 * K]))

Submission status: Runtime Error

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

happy = 0
for i in range(N-1):
  if S[i] == S[i+1]:
    happy += 1
return min([N-1, happy + 2 * K])

Submission status: Runtime Error

Solution code:
def calculate_happiness(S: str, N: int) -> int:
  if N == 1:
    return 0
  happiness = 0
  if S[0] == S[1] == 'R':
    happiness += 1
  if S[-1] == S[-2] == 'L':
    happiness += 1
  for i in range(1, N-1):
    if S[i] == S[i+1] == 'R':
      happiness += 1
    elif S[i] == S[i-1] == 'L':
      happiness += 1
  return happiness

def change_string(S: str, l: int, r: int) -> str:
  part = S[l:r+1][::-1].replace('R', '_')
  part = part.replace('L', 'R').replace('_', 'L')
  return S[:l] + part + S[r+1:]

N, K = list(map(int, input().split()))
S = input()
happiness = calculate_happiness(S, N)
opt_S = S
opt_happiness = happpiness
for k in range(K):
  S = opt_S
  for l in range(N-1):
    for r in range(l+1:N):
      new_S = change_string(S, l, r)
      happiness = calculate_happiness(new_S, N)
      if happiness > opt_happiness:
        opt_S = new_S
        opt_happiness = happiness
return(opt_happiness)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
s = input()
c = 0
for i in range(n-1):
  if s[i] == s[i+1]:
    c += 1
print(min(c + k*2, n-1)

Submission status: Runtime Error

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

now=S[0]
smartS=now
for subs in S:
    if now != subs:
        smartS+=subs
        now=subs

smartS = list(smartS)

if len(smartS)>=2:
    now=smartS[1]
    for i in range(K):
        smartS[2*i]=now
    
    count=0
    
    for i,subs in enumerate(smartS):
        if subs=="L":
            if i==0 :
                count+=1
            else:
                if smartS[i-1] != "L":
                    count+=1
        if subs=="R":
            if i==len(smartS)-1:
                count += 1
            else:
                if smartS[i+1] != "R":
                    count+=1
    print(N-count+1)
else:
    print(N-1)

Submission status: Runtime Error

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

RLcount=0
for i in range(1,len(S)):
    if S[i-1:i+1]=="RL":
        RLcount+=1


if RLcount > K:
    temp = (RLcount-K)
    NN = N-2*temp
if S[0]=="L":
    NN -= 1
if S[-1]=="R":
    NN -= 1
if RLcount < K:
    NN = N-1

print(int(NN))