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: Accepted

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
    if not sq:break
    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: Accepted

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

if s[0] == 'L' and s[n-1] == 'L':
    s = 'R' + s
    cnt = 0
    for i in range(n):
        if s[i] == 'R' and s[i+1] == 'L':
            cnt += 1
    if cnt <= k:
        print(n-1)
    elif cnt == k+1:
        print(n-1)
    else:
        print(n-2*(cnt-1)-1+2*k)

elif s[0] == 'L' and s[n-1] == 'R':
    s = 'R' + s + 'L'
    cnt = 0
    for i in range(n+1):
        if s[i] == 'R' and s[i+1] == 'L':
            cnt += 1
    if cnt <= k:
        print(n-1)
    elif cnt == k+1:
        print(n-1)
    elif cnt == k+2:
        print(n-2)
    else:
        print(n-2*(cnt-2)-2+2*k)

elif s[0] == 'R' and s[n-1] == 'L':
    cnt = 0
    for i in range(n-1):
        if s[i] == 'R' and s[i+1] == 'L':
            cnt += 1
    if cnt <= k:
        print(n-1)
    else:
        print(n-2*cnt+2*k)

elif s[0] == 'R' and s[n-1] == 'R':
    s = s + 'L'
    cnt = 0
    for i in range(n):
        if s[i] == 'R' and s[i+1] == 'L':
            cnt += 1
    if cnt <= k:
        print(n-1)
    elif cnt == k+1:
        print(n-1)
    else:
        print(n-2*(cnt-1)-1+2*k)

Submission status: Accepted

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

tmp = A[0]
cnt = 1
for i in range(1,N):
	if A[i] == tmp:
		if i != N-1:
			continue

	else:
		cnt += 1
		tmp = A[i]
		
t = cnt - (2*K)

if t > 0:
	ans = N-t
else:
	ans = N-1

print(ans)

Submission status: Accepted

Solution code:
import sys
n, k = map(int, input().split())
s = list(input())
left = 0
right = 0
if s[0] == "L":
    left = 1
if s[n-1] == "R":
    right = 1
count = 0
if n == 1:
    print(0)
    sys.exit()
for i in range(n-1):
    if s[i] == "R" and s[i+1] == "L":
        count += 1
if k < count:
    count -= k
    ans = n - count*2 - left - right
    print(ans)
elif k == count:
    if left == right == 1:
        print(n-2)
    else:
        print(n-1)
else:
    print(n-1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = list(input())
x = 0
y = 0
if s[0] == "L":
    y += 1
if s[n-1] == "R":
    y += 1 
for i in range(n-1):
    if s[i] == "R" and s[i+1] =="L":
        x += 1
if x >= k:
    print(n-(x-k)*2-y)
else:
    print(n-1)

Submission status: Accepted

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

LR = []
num = 1
now = S[0]

for i in range(1,N):
    if S[i] == now:
        num += 1
    else:
        now = S[i]
        LR.append(num)
        num = 1

LR.append(num)

length = len(LR)
print(N-length+min(2*K,length-1))

Submission status: Accepted

Solution code:
import itertools
N, K = map(int, input().split())
S = input()
A = list()
c = 0
for n in range(len(S)-1):
    if S[n] == S[n+1]:
        c += 1
print(min(c+2*K, N-1))

Submission status: Accepted

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

r = 0
happy = 0

for i in range(1, len(s)):
    if s[i-1] is not s[i]:
        if k is not 0:
            if r is 0:
                r = 1
            else:
                happy += 2
                r = 0
                k -= 1
    else:
        happy += 1

if r == 1:
    happy += 1
print(happy)

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    S = input()
    cnt = 0
    for i in range(N-1):
        if S[i] == 'R' and S[i] == S[i+1]:
            cnt += 1

    for i in range(N-1,0,-1):
        if S[i] == 'L' and S[i] == S[i-1]:
            cnt += 1

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

if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

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

flips = sum(int(x!=y) for x,y in zip(S,S[1:]))

flips = max(0,flips-2*K)
print(N-1-flips)

Submission status: Accepted

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

Submission status: Accepted

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


def solve(N: int, K: int, S: str):
    rep_ss = []
    check_c = S[0]
    cnt = 0
    for char in S:
        if check_c == char:
            cnt += 1
        else:
            rep_ss.append(cnt)
            cnt = 1
            check_c = char
    rep_ss.append(cnt)
    adj = 0
    if K >= len(rep_ss)//2:
        K = len(rep_ss) // 2
        if len(rep_ss) % 2 == 0:
            K -= 1
            adj = 1
    ans = N - len(rep_ss) + 2 * K + adj
    print(ans)
    return


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


if __name__ == '__main__':
    main()

Submission status: Accepted

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

if len(S) > 1:
    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) )
else:
    print(0)

Submission status: Accepted

Solution code:
from itertools import*

a,b=map(int,input().split())
s=input()
n=[len(list(v)) for k,v in groupby(s)]
print(min(sum(n)-len(n)+min(len(n)-1,b)*2,a-1))

Submission status: Accepted

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

same, other = 0, 0
for i in range(N - 1):
    if S[i] == S[i + 1]:
        same += 1
    else:
        other += 1

if (other + 1) // 2 <= K:
    print(same + other)
else:
    print(same + 2 * K)

Submission status: Accepted

Solution code:
import re
N, K = map(int, input().split())
S = input()
s_arr = list(map(len, re.findall(r'R+|L+',S)))
not_happies = len(s_arr)
happys = not_happies - K
if (not_happies-1)/2 <= K:
    ans = N-1
else:
    ans = N - (not_happies - 2*K)
print(ans)

Submission status: Accepted

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)

Submission status: Accepted

Solution code:
l,k=map(int,input().split())
s=input()+'?'
ss=[]
prev=0
for i in range(l):
  if s[i]!=s[i+1]:
    ss.append(s[prev:i+1])
    prev=i+1
ll=len(ss)
s2=''
cnt=0
for i in range(ll):
  if i%2==0:
    s2+=ss[i]
  else:
    if cnt<k:
      cnt+=1
      if ss[i][0]=='R':
        s2+='L'*len(ss[i])
      else:
        s2+='R'*len(ss[i])
    else:
      s2+=ss[i]
s2+='?'
ans=0
cnt=0
for i in range(l):
  if s2[i]==s2[i+1]:
    cnt+=1
  else:
    ans+=cnt
    cnt=0
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
S = input()
cnt = 0

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

Submission status: Accepted

Solution code:
import sys
import math

def input():
    return sys.stdin.readline()[:-1]

def main():
    N, K = map(int,input().split())
    S = "_" + input() + "_"
    if N == 1:
        print(0)
        exit(0)
    LR = 0
    ans = 0
    for k in range(1,N+1):
        if S[k] == S[k+1]:
            ans += 1
        else:
            LR += 1

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

n, k = li()
s = ns()

if len(set(list(s))) == 1:
    print(n-1)
else:
    init = 0
    bef = ""
    for si in s:
        if si == bef:
            init += 1
        bef = si
    print(min(n-1, init + 2*k))

Submission status: Accepted

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

before = S[0]
div = 0

for s in S[0:]:
    if s != before:
        div += 1
    before = s

print(N-1-max(0, div-(2*K)))

Submission status: Accepted

Solution code:
# ABC140 D - Face Produces Unhappiness

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

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

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split(" "))
s = input()
score = 0
for i in range(len(s) - 1):
    if s[i] == s[i+1]:
        score += 1

score = min(score + 2*k, n - 1)
print(score)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
hoge=list(input())
hap=0
for i,j in zip(hoge[0:],hoge[1:]):
  if i==j:hap+=1
print(min(hap+2*k,n-1))

Submission status: Accepted

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

Submission status: Accepted

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

count = len(S) - 1
mismatch = 0
for idx in range(len(S) - 1):
	if(S[idx] != S[idx+1]):
		mismatch += 1
mismatch = max(0, mismatch - 2 * K)
print(count - mismatch)

Submission status: Accepted

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

lr = 0
f=0

if s[0] == 'R':
  lr+=1
  f +=1
for i in range(n-1):
  if s[i] == 'L' and s[i+1] == 'R':
    lr += 1
if s[n-1]=='L':
  lr+=1
  f +=1

if k<lr-1:
  print(n-2*(lr-k)+f)
elif k==lr-1:
  print(n-1 if f>0 else n-2)
else:
  print(n-1)

Submission status: Accepted

Solution code:
n,k = list(map(lambda x:int(x),input().split()))
s = input()
if len(s) == 1:
    print(0)
    exit(0)
prev = ''
ans = ''
count = -1
flag = True
for i in range(len(s)):
    if s[i] != prev:
        count += 1
        prev = s[i]
        if count %2 == 1:
            k -= 1
            if k < 0:
                flag = False
                
    if count%2 == 1 and flag:
        if s[i] == 'L':
            ans += 'R'
        else:
            ans += 'L'
    else:
        ans += s[i]

count = 0
for i in range(1,len(ans)-1):
    if ans[i] == 'L' and ans[i-1] == 'L':
        count += 1
    elif ans[i] == 'R' and ans[i+1] == 'R':
        count += 1
if ans[0] == 'R' and ans[1] == 'R':
    count += 1
if ans[-1] == 'L' and ans[-2] == 'L':
    count += 1
print(count)

Submission status: Accepted

Solution code:

def main():
    N, K = [int(x) for x in input().split()]
    LR = input()

    count = 0
    for p in range(len(LR)-1):
        if LR[p] == LR[p+1]:
            count += 1
    
    count += K*2
    count = min(count, N-1)

    print(count)


if __name__ == "__main__":
    main()

Submission status: Accepted

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-1):
    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: Accepted

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

unhappy_0=s.count('RL')*2+(s[0]=='L')+(s[-1]=='R') #正誤判定式は、1か0の数値として使える
print(n-max(unhappy_0-k*2,1))

Submission status: Accepted

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

happy = 0

for i, s in enumerate(S):
    if s == "L":
        if i != 0 and S[i - 1] == "L":
            happy += 1
    else:
        if i != N - 1 and S[i + 1] == "R":
            happy += 1
print(min(N - 1, happy + 2 * K))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
N, K = map(int, input().split())
S = input()

cnt1 = 0
cnt2 = 0

for i in range(N-1):
    # edge
    if i == 0 and S[i] == 'L':
        cnt1 += 1
    if i == N-2 and S[i+1] == 'R':
        cnt1 += 1 

    # not edge
    if S[i] == S[i+1]:
        continue
    elif S[i] == 'L' and S[i+1] == 'R':
        continue
    elif S[i] == 'R' and S[i+1] == 'L':
        cnt2 += 1

if cnt2 >= K:
    print(min(N-1, N - (cnt2-K)*2 - cnt1))
else:
    print(min(N-1, N - max(0, (cnt1 - (K - cnt2)))))

Submission status: Accepted

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

cnt = n - 1 - s.count('LR') - s.count('RL')
ans = min(n - 1, 2 * k + cnt)
print(ans)

Submission status: Accepted

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

# 同じ方向を向いている人の圧縮処理                                                       
S_pack = [S[0]]
for direction in S:
    if S_pack[-1] != direction:
        S_pack.append(direction)
n_unhappy = len(S_pack)
n_unhappy = max(n_unhappy - K*2, 1)

print(N - n_unhappy)

Submission status: Accepted

Solution code:
# 不幸な人の最少人数は1人
# 同じ向きを向いている人を1人に圧縮すると、[L,R,L,...,L], [L,R,L,...,R],[R,L,R,...,R],[R,L,R,...,L]のいずれかの配列が得られる
# 不幸な人が2人以上いれば、1回操作を行うごとに不幸な人を2人減らせる。不幸な人が1人になったら終了

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

# 同じ方向を向いている人の圧縮処理
S_pack = [S[0]]
for direction in S:
    if S_pack[-1] != direction:
        S_pack.append(direction)

n_unhappy = len(S_pack)
n_unhappy = max(n_unhappy - K*2, 1)

print(N - n_unhappy)

Submission status: Accepted

Solution code:
# 不幸な人の最少人数は1人
# 同じ向きを向いている人を1人に圧縮すると、[L,R,L,...,L], [L,R,L,...,R],[R,L,R,...,R],[R,L,R,...,L]のいずれかの配列が得られる
# [L,R,L,...,L], [R,L,R,...,R]については1回操作を行うごとに不幸な人が常に2人減る。(配列長-2)回操作を行ったら終了
# [L,R,L,...,R], [R,L,R,...,L]については、(配列長)/2)回目の操作のみ不幸な人を1人だけ減らし、他の操作では2人不幸な人を減らす

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

# 同じ方向を向いている人の圧縮処理
S_pack = [S[0]]
for direction in S:
    if S_pack[-1] != direction:
        S_pack.append(direction)

n_unhappy = len(S_pack)

if n_unhappy%2 == 1:
    n_unhappy = max(n_unhappy - K*2, 1)
elif K >= n_unhappy/2:
    n_unhappy = 1
else:
    n_unhappy -= K*2

print(N - n_unhappy)

Submission status: Accepted

Solution code:
# 今回の方針
# LRの境界の数だけで計算を済ませる

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

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

happy += 2*k
if happy >= n:
    happy = n-1

print(happy)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
cnt=0
for i in range(n-1):
    if s[i]!=s[i+1]:
        cnt+=1
order=0
left=0
if cnt%2==0:
    order=cnt//2
elif cnt%2!=0:
    order=cnt//2
    left=1
checker=s[0]
count=0
lists=[]

s=s+"e"
for i in range(n+1):
    if s[i]==checker:
        count+=1
    elif s[i]!=checker:
        lists.append(count-1)
        count=1
        checker=s[i]
base=sum(lists)

if order>=k:
    ans=k*2+base
elif order<k:
    ans=n-1
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = input()
key = s[0]
count = 0
for i in range(1,n):
    if key == s[i]:
        count += 1
    else:
        key = s[i]

ans = count+2*k
if ans >= n:
    print(n-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-


def main():
  _, k = map(int, input().split())
  vs = [int(v == 'L') for v in input().strip()]
  h = sum(int(a == b) for a, b in zip(vs[:-1], vs[1:]))
  print(min(h + 2 * k, len(vs) - 1))


if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
N ,K = map(int, input().split())
S = input()
kirikae = 0
kirikae2 = 0
flag = 0
for i in range(N-1):
    if S[i] != S[i+1]:
        kirikae += 1
kirikae = kirikae - (K * 2)
if kirikae <= 0 :
    kirikae = 0

print(N - 1 - kirikae)

Submission status: Accepted

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

if __name__ == '__main__':
    solve()

Submission status: Accepted

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

num_group = 1
for p1, p2 in zip(s, s[1:]):
    if p1 != p2:
        num_group += 1

score = min(n - 1, n - (num_group - 2 * k))

print(score)

Submission status: Accepted

Solution code:
from math import ceil
N, K = map(int, input().split())
S = 'x' + input() + 'x'

ans = 0
X = ''
ns = ''

for i, s in enumerate(S[1:-1], start=1):
    if s == 'L':
        if S[i - 1] == 'L':
            ans += 1
        else:
            X += s

    else:
        if S[i + 1] == 'R':
            ans += 1
        else:
            X += s


target = 'L' if X[0] == 'R' else 'R'
k_cnt = 0
for i, x in enumerate(X):
    if x == target and k_cnt < K:
        k_cnt += 1
        if i == len(X) - 1:
            ans += 1
        else:
            ans += 2

print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
def MAP(): return list(map(int,input().split()))
def INT(): return int(input())
def FLOAT(): return float(input())
MOD = 10**9+7

n,k = MAP()
s = input()
unhappy=0
if s[0]=="L":
    unhappy+=1
if s[n-1]=="R":
    unhappy+=1

for i in range(n-1):
    if s[i:i+2]=="RL":
        unhappy+=2
print(n-max(1,unhappy-(2*k)))

Submission status: Accepted

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

ans = 0

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(pow(10, 6))


def main():
    n, k = map(int, input().split())
    s = input().strip()
    prevs = s[0]
    la = [0]
    for _s in s:
        if prevs == _s:
            la[-1] += 1
        else:
            la.append(1)
            prevs = _s
    
    ans = 0
    is_swap = False
    for i in range(0, len(la), 2):
        ans += la[i]-1
        if is_swap:
            ans += 1
            is_swap = False
        if i+1 < len(la) and k >= 1:
            ans += la[i+1]
            k -= 1
            is_swap = True
        elif i+1 < len(la):
            ans += la[i+1]-1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import math
import numpy as np
# from functools import lru_cache

args = sys.argv
if len(args) == 2:
  from IPython import embed
  em = True
else:
  em = False

#### input
N, K = map(int, input().split())
S = input()
# a = list(map(int, input().split()))
# a = list(map(lambda x: int(x)*(-1), a))  # 各要素を-1倍


# n = int(input())
# t = [int(input()) for i in range(n)]
if em: sys.stdin = open('/dev/tty')

#### functions
# @lru_cache(maxsize=10000)

#### process
# if em: embed()

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

num_R = len([s for s in S if s == "R"])

if num_R > len(S) / 2:
  S2 = S.split("R")
else:
  S2 = S.split("L")

edge     = len([s for s in [S2[0],S2[-1]] if s != ""])
non_edge = len([s for s in S2[1:-1] if s != ""])

# if em:embed()

score = score + 2 * min(K, non_edge)
K = K - min(K, non_edge)
score = score + min(K, edge)

print(score)

## heapsort, O(logN)
# import heapq
# heapq.heapify(A)
# min = heapq.heappop(A)
# heapq.heappush(A, new_element)

Submission status: Accepted

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

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

Submission status: Accepted

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

for i in range(len(S)):
  if S[i] == "L":
    S[i] = 0
  else:
    S[i] = 1

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

ans = count + 2 * K
if ans > len(S) - 1:
  ans = len(S) - 1
print(ans)

Submission status: Accepted

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

if s[0] == 'R':
    left_happy = 1
else:
    left_happy = 0
if s[-1] == 'L':
    right_happy = 1
else:
    right_happy = 0
edge_happy = left_happy + right_happy

renzoku = 0
original_happy = 0
before = 0
unhappy = 0
for i in range(n):
    now = s[i]
    if before == now:
        renzoku += 1
    else:
        original_happy += renzoku
        renzoku = 0
    if before == 'R' and now == 'L':
        unhappy += 1
    before = now
original_happy += renzoku

if edge_happy == 0:
    if k <= unhappy:
        print(original_happy + k*2)
    else:
        print(original_happy + unhappy*2 + 1)
elif edge_happy == 1:
    if k <= unhappy:
        print(original_happy + k*2)
    else:
        print(original_happy + unhappy*2)
else:
    if k < unhappy:
        print(original_happy + k*2)
    else:
        print(original_happy + unhappy*2 - 1)

Submission status: Accepted

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*K, N-1))

Submission status: Accepted

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

def g(t):
    l = []
    b = "x"
    c = 0
    for i, t_i in enumerate(t):
        if b != t_i:
            l.append(c)
            c = 0
        c += 1
        b = t_i
    l.append(c)
    return l[1:]

l = g(S)
len_l = len(l)
score = sum(l)-len_l

score += min(len_l//2, K)*2 - (len_l%2==0 and len_l//2 <= K)

print(score)

Submission status: Accepted

Solution code:
# 入力を受け取る
N, K = input().strip().split()
N, K = [int(N), int(K)]
S = [None] + list(input().strip())

# 操作前のSの中でR→L, L→Rの切り替えの数、幸福な人の数を数える。
# 例えば、'RLR'の場合は2
num_dirchange = 0  # 切り替えの数
num_happy = 0
for i in range(1, N+1): # i = 1, 2, ..., N
    # 方向切り替えの数
    if i > 1 and S[i] is not S[i-1]:
        num_dirchange += 1
    # 幸福な人の数
    if S[i] is 'L':
        if i > 1 and S[i-1] is 'L':
            num_happy += 1
    if S[i] is 'R':
        if i < N and S[i+1] is 'R':
            num_happy += 1

# 1回の操作で2箇所の切り替えを減らすことができ、
# 幸福な人を2人増やすことができる。
# つまり、切り替えの数が2*K以上の場合は、K回の操作で幸福な人を2*K人増やせる
if num_dirchange >= 2 * K:
    num_happy = num_happy + 2*K
else:
    num_happy = N - 1  # RRR...Rの場合右端、LLL...Lの場合左端の人以外は幸福

print(num_happy)

Submission status: Accepted

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

h = 0
lr = 0
rl = 0
for i in range(1,N):
  if S[i-1] == S[i] :
    h += 1
  elif S[i-1] == 'L' and S[i] == 'R':
    lr += 1
  else:
    rl += 1
#print(h,lr,rl)

while (K>0 and (lr>0 or rl>0)):
  if lr > 0:
    lr -= 1
    h += 1
  if rl > 0:
    rl -= 1
    h += 1
  K -= 1
print(h)

Submission status: Accepted

Solution code:
if __name__=='__main__':
    a = [int(i) for i in input().split(' ')]
    n = a[0]
    k = a[1]
    s = input()
    cnt = 0
    ans = 0
    for i in range(len(s)-1):
        if s[i] != s[i+1]:
            cnt += 1
        else:
            ans += 1
    if cnt > 2*k:
        ans += k*2
    if cnt <= 2*k:
        ans = len(s)-1
    print(ans)

Submission status: Accepted

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

    score = 0
    s = S[0]
    for i in range(1, N):
        t = S[i]
        if s == t:
            score += 1
        s = t
    ans = min(score + 2 * K, N - 1)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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


def solve(N: int, K: int, S: str):
    Y = 0
    X = 0

    if S[0] == "L":
        Y += 1
    if S[-1] == "R":
        Y += 1

    for i in range(len(S)-1):
        if S[i:i+2] == "RL":
            X += 1

    H = len(S) - 2 * X - Y
    H += min(K,X) * 2
    if K-X > 0:
        H += min(K-X, Y) 

    H = min(len(S)-1, H)

    print(H)



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

if __name__ == '__main__':
    main()

Submission status: Accepted

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, t + 2 * k]))

Submission status: Accepted

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
			
	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: Accepted

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7

def solve(f):
    n, k = f.read_int_list()
    s = f.read_str()

    diff = 0
    for i in xrange(n-1):
        if s[i] != s[i+1]:
            diff += 1

    return n-1-max(0, diff-2*k)


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Submission status: Accepted

Solution code:
#R…LやL…Rを選んでも意味がない
#L…L、R…Rを選んで反転（R…R、L…Lに）
#RL…LRを反転させると2増える
#LR…RLを反転させると2増える
#RLとLRとをそれぞれ数え上げ、min(RL数,LR数,K)を取ればよい
#例外としてLRorRLと端っこを反転したとき、1増える
#abs(LR-RL)=1 & K-min(RL,LR)>=1なら+1
#abs(LR-RL)>=1 & K-min(RL,LR)=1なら+1
#abs(LR-RL)>1 & K-min(RL,LR)>1なら+2
N,K = map(int,input().split())
S = input()
LL = 0
RR = 0
LR = 0
RL = 0
for i in range(N-1):
    if S[i]=="L" and S[i+1]=="L":
        LL += 1
    if S[i]=="R" and S[i+1]=="R":
        RR += 1
    if S[i]=="L" and S[i+1]=="R":
        LR += 1
    if S[i]=="R" and S[i+1]=="L":
        RL += 1
ans = 0
Kaisu = min(LR,RL,K)
ans += LL+RR+Kaisu*2

if abs(LR-RL)==1 and K-min(RL,LR)>=1:
    ans += 1
elif abs(LR-RL)>1 and K-min(RL,LR)==1:
    ans += 1
elif abs(LR-RL)>1 and K-min(RL,LR)>1:
    ans += 2

print(ans)