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:
from _collections import deque


def parser():
    while 1:
        data = list(input().split(' '))
        for number in data:
            if len(number) > 0:
                yield (number)


input_parser = parser()


def gw():
    global input_parser
    return next(input_parser)


def gi():
    data = gw()
    return int(data)


MOD = int(1e9 + 7)

import numpy
import scipy
from collections import deque
#https://atcoder.jp/contests/abc141/tasks/abc141_d
#D - Powerful Discount Tickets
"""
need to consider the case that ticket is not enough to lower everything
"""
N = gi()
K = gi()
S = gw()

seg_cnt = 0
for i in range(0, N - 1):
    if S[i] != S[i + 1]:
        seg_cnt += 1

cur_happy = N - 1 - seg_cnt

if 2 * K >= seg_cnt:
    ans = N - 1
else:
    ans = cur_happy + 2 * K

print(ans)

Submission status: Accepted

Solution code:
# ABC-140-D
N, K = map(int, input().split())
S = input()
ans = 0

#初期値を確認する。
for i in range(0, len(S)-1):
    if S[i] == S[i+1]:
        ans += 1

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

Submission status: Accepted

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

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

Submission status: Accepted

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

    prev = "s"
    count = 0
    for s in S:
        if prev != s:
            count += 1
            prev = s
    print(min(N + 2 * K - count, N - 1))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

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

g = S[0]
cnt = 0
for s in S:
    if s == g:
        cnt += 1
    else:
        T.append(cnt)
        cnt = 1
        g = s
else:
    T.append(cnt)


print(N - max(1, len(T) - 2 * K))

Submission status: Accepted

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

g = S[0]
cnt = 0
for s in S:
    if s == g:
        cnt += 1
    else:
        T.append(cnt)
        cnt = 1
        g = s
else:
    T.append(cnt)


t = len(T)
for k in range(K):
    t -= 2

if t <= 1:
    print(N - 1)
else:
    print(N - t)

Submission status: Accepted

Solution code:
n, k = [int(_) for _ in input().split()]
s = input()
c = 0
ans = 0
new_s = '' + s[0]
for i in range(1, n):
    if s[i] == s[i - 1]:
        c += 1
    else:
        ans += c
        c = 0
        new_s += s[i]
if c != 0:
    ans += c

length = len(new_s)
l = []
if length == 2:
    l = [1]
if length >= 3:
    if length % 2 == 1:
        l = [2] * (length // 2)
    else:
        l.append(1)
        l += [2] * ((length // 2) - 1)

if len(l) >= k:
    for i in range(k):
        ans += l.pop()
else:
    for i in range(len(l)):
        ans += l.pop()
print(ans)

Submission status: Accepted

Solution code:
import sys
import math
import heapq
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()
def II(): return int(input())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res
def gcd(x, y):
    if x < y: x, y = y, x
    div = x % y
    while div != 0:
        x, y = y, div
        div = x % y
    return y

N,K=LI()
S=input()

cnt = 0
lst = None
RNGS=[]
for i in range(N):
    if lst and lst != S[i]:
        RNGS.append((lst, cnt))
        cnt = 0
    cnt += 1
    lst = S[i]
RNGS.append((lst, cnt))

# print(RNGS)

mod_cnt = 0
if len(RNGS) >= 3:
    for i in range(0, len(RNGS)-2, 2):
        if mod_cnt < K:
            lr, num = RNGS[i+1]
            lr = 'L' if lr ==  'R' else 'R'
            mod_cnt += 1
            RNGS[i+1] = (lr, num)

# print(RNGS)
if mod_cnt < K:
    print(len(S) - 1)
else:
    prev = None
    res = 0
    for i in range(len(RNGS)):
        lr, num = RNGS[i]
        res += num
        if not prev or prev != lr:
            res -= 1
        prev = lr
    print(res)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n,k = map(int, input().split())
s = input()

rl = 0
for i in range(n-1):
    if s[i:i+2]=="RL":
        rl += 1

if k>rl:
    print(n-1)
else:
    res = n - 2*(rl-k)
    if s[0]=="L":
        res -= 1
    if s[n-1]=="R":
        res -= 1

    print(res)

Submission status: Accepted

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

Submission status: Accepted

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

cLR=0
cRL=0
oLR=0
oRL=0

if row[0]=="L":
    oRL+=1
else:
    oLR+=1
    
if row[-1]=="L":
    oLR+=1
else:
    oRL+=1

happiness=0
for i in range(n-1):
    a=row[i]
    b=row[i+1]
    if a=="L" and b=="R":
        cLR+=1
    elif b=="L" and a=="R":
        cRL+=1
    else:
        happiness+=1
    

if min(cLR,cRL)>=k:
    ans=happiness+k*2 
elif cLR>cRL and cRL+1==k:
    ans=happiness+cRL*2+1
elif cLR<cRL and cLR+1==k:
    ans=happiness+cLR*2+1
elif cLR>cRL:
    ans=happiness+cRL*2+min(oRL,cLR-cRL)
elif cLR<cRL:
    ans=happiness+cLR*2+min(oLR,cRL-cLR)
else:
    ans=happiness+cLR*2 
    
print(ans)

Submission status: Accepted

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

ends = 0
middle = 0

now = S[0]
if now == 'L':
  ends += 1

_S = S[1:]
for i, s in enumerate(_S):
  if now == 'R' and s == 'L':
    middle += 2
  
  now = s

if now == 'R':
  ends += 1

ans = N - max(middle+ends-2*K, 1)
print(ans)

Submission status: Accepted

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

point=0
gap=0
for i in range(N-1):
    if S[i+1] == S[i]:
        point+=1
    else:
        gap+=1

if gap % 2 ==0:
    if K >= gap/2:
        point+=gap
    else:
        point+=K*2
else:
    if K >= gap//2+1:
        point+=gap
    else:
        point+=K*2
print(point)

Submission status: Accepted

Solution code:
import sys


def solve():
    input = sys.stdin.readline
    mod = 10 ** 9 + 7
    n, k = list(map(int, input().rstrip('\n').split()))
    s = str(input().rstrip('\n'))
    cnt = 0
    for i in range(1, n):
        if s[i] == s[i-1]:
            cnt += 1
    print(min(n - 1, cnt + k * 2))


if __name__ == '__main__':
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N,K=map(int,input().split())
S=list(input())

l=[]
count=1
for i in range(N-1):
    if S[i]!=S[i+1]:
        l.append(count)
        count=1
    else:
        count+=1
l.append(count)

flag=False
ans=0
idx=0
time=0
while idx<len(l):
    if time<K:
        time+=1
        ans+=(l[idx]+l[idx+1] if idx!=(len(l)-1) else l[idx])
        idx+=1
    else:
        flag=True
        ans+=(l[idx]-1)
        
    idx+=1

if flag:
    print(ans)
else:
    print(ans-1)

Submission status: Accepted

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

happy_count = 0
pre = ''
for index in range(n - 1):
  if s[index + 1] == s[index]:
    happy_count += 1

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

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
S = input()
prev = "s"
count = 0
for s in S:
    if prev != s:
        count += 1
        prev = s
print(min(N + 2 * K - count,N - 1))

Submission status: Accepted

Solution code:
import sys

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

count = 0

if N==1:
    print(0)
    sys.exit()

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

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from itertools import groupby
def resolve():
    n,k=map(int,input().split())
    S=input()
    score=0
    for key,it in groupby(S):
        score+=len(list(it))-1

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

Submission status: Accepted

Solution code:
(lambda T,S: (lambda O,N,K :(lambda
P:(lambda U :print ( sum(map(lambda
i: (lambda j :(0<=j<N)and(U[i]==U[j
]))(i-1+(U[i]=="R")*2),range(N)))))
(''.join( [ ( lambda X,V :[X,("R"if
X[0] == "L" else "L" )*len(X) ][ V%
2 and V//2<P] ) ( O[k],k ) for k in
range( len(O) ) ] ) ))( min( len(O)
//2,K )))(__import__("re").findall(
r"(R+|L+)",S),T[0],T[1]))(tuple(map
( int,input().split() )), input() )

Submission status: Accepted

Solution code:
(lambda NK,S:
    (lambda N,K,O:
        (lambda P:
            (lambda Sdash:print(
                    sum(map(
                            lambda i:(lambda j:(0<=j<N)and(Sdash[i]==Sdash[j]))(i-1+(Sdash[i]=="R")*2)
                            ,
                            range(N)
                    ))
            ))(''.join(
                [
                    (
                        lambda val,key:[val,("R"if val[0]=="L"else"L")*len(val)][key%2 and key//2<P]
                    )(O[k],k)
                        for k in range(len(O))]
            ))
        )(
            min(len(O)//2,K)
        )
    )(
        NK[0],NK[1],__import__("re").findall(r"(R+|L+)",S)
    )
)(
    tuple(map(int,input().split())),input()
)

Submission status: Accepted

Solution code:
(lambda NK,S:
    (lambda N,K,O:
        (lambda P:
            (lambda Sdash:print(
                    sum(map(
                            lambda i: (lambda j:(0 <= j < N) and (Sdash[i] == Sdash[j]))(i + (-1 if Sdash[i] == "L" else 1))
                            ,
                            range(N)
                    ))
            ))(''.join(
                [
                    (
                        lambda val,key:[val,("R" if val[0] == "L" else "L")*len(val)][key%2 and key//2<P]
                    )(O[k],k)
                        for k in range(len(O))]
            ))
        )(
            min(len(O)//2,K)
        )
    )(
        NK[0],NK[1],__import__("re").findall(r"(R+|L+)",S)
    )
)(
    tuple(map(int,input().split())),input()
)

Submission status: Accepted

Solution code:
NK = tuple(map(int,input().split()))
S = input()
N = NK[0]
K = NK[1]
O = __import__("re").findall(r"(R+|L+)",S)
P = min(len(O)//2,K)
Sdash = ''.join(
    [(
        lambda val,key:[val,("R" if val[0] == "L" else "L")*len(val)][key%2 and key//2<P]
        )(O[k],k)
        for k in range(len(O))]
)
print(sum(map(
    lambda i: (lambda j:(0 <= j < N) and (Sdash[i] == Sdash[j]))(i + (-1 if Sdash[i] == "L" else 1))
    ,range(N))))

Submission status: Accepted

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

O = __import__("re").findall(r"(R+|L+)",S)
P = min(len(O)//2,K)
for k in range(len(O)):
    if not(k % 2 and k // 2 < P):
        continue
    O[k] = (lambda OO:("R" if OO[0] == "L" else "L")*len(OO))(O[k])

Sdash = ''.join(O)
happy = lambda i: (lambda j:(0 <= j < N) and (Sdash[i] == Sdash[j]))(i + (-1 if Sdash[i] == "L" else 1))

print(sum(map(happy,range(N))))

Submission status: Accepted

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

O = re.findall(r"(R+|L+)",S)
for j in range(min(len(O)//2,K)):
    k = j * 2 + 1
    OO = O[k]
    O[k] = ("R" if OO[0] == "L" else "L")*len(OO)

Sdash = ''.join(O)
def happy(i):
    j = i + (-1 if Sdash[i] == "L" else 1)
    return (0 <= j < N) and (Sdash[i] == Sdash[j])

print(sum(map(happy,range(N))))

Submission status: Accepted

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

s = str(input())

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

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

n, k = ril()
s = rs()
m = 1
for c0, c1 in zip(s, s[1:]):
    if c0 != c1:
        m += 1
if m <= 2 * k:
    print(n - 1)
else:
    print(n - m + 2 * k)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]


def rle(s):
    import itertools
    return list(map(lambda x: (x[0], len(list(x[1]))), itertools.groupby(s)))


n, k = ril()
s = rs()
s = rle(s)
m = len(s)
if m <= 2 * k:
    print(n - 1)
else:
    print(n - m + 2 * k)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
initial_happiness = 0
left = 'X'
for c in s:
    initial_happiness += 1 if c == left else 0
    left = c
ans = min(n-1, initial_happiness + 2*k)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
grp = 0
now = ""
for c in s:
  if c != now:
    grp += 1
    now = c
hap = 0
for i in range(n):
  if (i>0 and s[i]=='L' and s[i-1]=='L') or (i<n-1 and s[i]=='R' and s[i+1]=='R'):
    hap += 1
p_2 = (grp - 1) // 2
p_1 = (grp + 1) % 2
print(hap + 2 * min(k, p_2) + int(k > p_2) * p_1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import groupby
d = {"R": "L", "L": "R"}
N, K = map(int, input().split())
S = input()
A = [(s,len(list(it))) for s, it in groupby(S)]
A = [(d[s], l) if i & 1 and i//2 < K else (s, l) for i, (s, l) in enumerate(A)]
S = "".join(s*l for s, l in A)
print(N - len(list(groupby(S))))

Submission status: Accepted

Solution code:
from collections import defaultdict,deque, Counter
import sys,heapq,bisect,math,itertools,string,queue,copy,time
import numpy as np
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
ans = 0

[n,k] = inpl()
s = input()
change = 0
nochange = 0
for i in range(1,len(s)):
    if s[i]!= s[i-1]: change += 1
    else: nochange += 1

if change//2 < k: ans = nochange + change
else: ans = nochange + 2*k

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from itertools import groupby
## 幸福数はN-group数
def solve(N: int, K: int, S: str):
    groups = groupby(S)
    compress = []
    for key,group in groups:
        compress.append(key)

    print(min(N-1,N-(len(compress)-2*K)))

    
    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 = input()

happiness = 0

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

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

Submission status: Accepted

Solution code:
from itertools import groupby
from collections import deque
N, K = map(int, input().split())
S = [len(list(g)) for k, g in groupby(input())]
S = deque(S)
i = 0
while i < K and len(S) > 2:
    S.append(S.pop() + S.pop() + S.pop())
    i += 1
if i < K and len(S) == 2:
    S.append(S.pop() + S.pop())
print(sum(S) - len(S))

Submission status: Accepted

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

LR = S.count("LR")

ans = 0

for i in range(N):
    if S[i] == "L":
        if i == 0:
            pass
        else:
            if S[i-1] == "L":
                ans += 1
    else:
        if i == N-1:
            pass
        else:
            if S[i+1] == "R":
                ans += 1


print(min(N-1,ans+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 = min(n - 1, cnt + 2 * k)
print(ans)

Submission status: Accepted

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

joint = 0
cnt = 0
for i in range(1,n):
  if s[i - 1] == s[i] == 'L':
    cnt += 1

for i in range(n - 1):
  if s[i + 1] == s[i] == 'R':
    cnt += 1

for i in range(n-1):
  if s[i] != s[i + 1]:
    joint += 1
  
if joint % 2 == 0:
  cnt += min(2*k, joint)
else:
  if k <= joint // 2:
    cnt += k * 2
  else:
    cnt += joint

print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = str(input())
S = 'R' + S + 'L' # N+2

M1 = 0 # +2できる場所
M2 = 0 # +1できる場所
for n in range(N+1):
  if S[n]+S[n+1] == 'RL':
    if n == 0 or n == N:
      M1 += 1
    else:
      M2 += 1
      
cur_h = N - (M2*2) - (M1*1)
if cur_h == N-1:
    print(cur_h)
    exit()


if K < M2:
  res = cur_h + 2*K
elif M2 <= K and K < M2+M1:
  res = cur_h + 2*M2 + 1*(K-M2)
else:
  res = cur_h + 2*M2 + 1*M1

if res == N:
  res -= 1
print(res)

Submission status: Accepted

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

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

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

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

Submission status: Accepted

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

# 向かい合ってるor背を向けてる場所を検知
num_diff = 0
pre_s = S[0]
for cur_s in S[1:]:
    if pre_s != cur_s:
        num_diff += 1
    pre_s = cur_s

for i in range(K):
    if num_diff <= 1:
        num_diff = 0
        break
    num_diff -= 2

print(N-1-num_diff)

Submission status: Accepted

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

flag = 0

happiness = 0

for i in range(N - 1):
    if S[i] == S[i + 1]:
        happiness += 1
    else:
        if flag == 0 and K > 0:
            K -= 1
            flag = 1
        elif flag == 1:
            flag = 0
            happiness += 2

print(happiness + flag)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
segment = 0
now = '#'
ans = 0
for i in 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: Accepted

Solution code:
N,K=map(int,input().split())
S=str(input())
P=[1]
for i in range(1,N):
  if S[i]==S[i-1]:
    P[-1] +=1
  else:
    P +=[1]
if K*2<N:
  P=[sum(P[:2*K+1])]+P[2*K+1:]
  answer = sum(P)-len(P)
else:
  answer=N-1
print(answer)

Submission status: Accepted

Solution code:
#coding: utf-8
import math
import heapq
import bisect

MOD = 10**9+7

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

# 複数個の数値を、intの配列として取得
S = input()

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, S):
    S = [c for c in S]

    idx = []
    p = (None, -1)
    for i, c in enumerate(S):
        if p[0] != c:
            idx.append([p[0], i-p[1]])
            p = (c, i)
    idx.append([p[0],len(S)-p[1]])
    idx.pop(0)
    
    
    ans = [idx[0]]
    for i in range(1, len(idx)):
        if i % 2 == 0:
            if ans[-1][0] == idx[i][0]:
                ans[-1][1] += idx[i][1]
            else:
                ans.append(idx[i])
        else:
            if K > 0:
                ans[-1][1] += idx[i][1]
                K -= 1
            else:
                ans.append(idx[i])
    a = 0
    for _, v in ans:
        a += v - 1
    return a


def main():
    N, K = read_int_n()
    S = read_str()
    print(slv(N, K, S))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
S = list(input())
ans=0
cnt=0
for i in range(n-1):
    if S[i]!=S[i+1]:
        cnt+=1
    else:
        ans+=1

if cnt <= k*2:
    print(n-1)
else:
    print(ans+k*2)

Submission status: Accepted

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

lis=[]
c=1
for i in range(n-1):
    if s[i+1]==s[i]:
        c+=1
    else:
        lis.append(c)
        c=1
    if i==n-2:
        lis.append(c)

n_faced=len(lis)//2
if s[0]=="L" and  s[-1]=="R":
    n_faced-=1

n_unhappy=2*n_faced
if s[0]=="L":    n_unhappy+=1
if s[-1]=="R":    n_unhappy+=1

print(n-max(n_unhappy-2*k,1))

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys


def solve():
    input = sys.stdin.readline
    mod = 10 ** 9 + 7
    n, k = list(map(int, input().rstrip('\n').split()))
    s = str(input().rstrip('\n'))
    cnt = 0
    for i in range(1, n):
        if s[i-1] == s[i]:
            cnt += 1
    print(min(n - 1, cnt + k * 2))


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from collections import deque
N,K = list(map(int,input().split()))
S = list(input())
S = deque(S)
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 len(S_2) == 1:
    print(ans) 
elif len(S_2) == 2:
    if S_2[0] == S_2[1] or K == 0:
        print(ans)
    else:
        print(ans + 1)
else:
    if S_2[0] != S_2[1] and S_2[-1] != S_2[-2] and K > 1:
        print(ans + 2)
    elif K == 0 or (S_2[0] == S_2[1] and S_2[-1] == S_2[-2]):
        print(ans)
    else:
        print(ans + 1)

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
N,K = map(int,input().split(' '))
S = input()
if S[0] == 'L':
    search_s = 'R'
    non_search_s = 'L'
else:
    search_s = 'L'
    non_search_s = 'R'
i = 0
new_S = ''
previous_s = S[0]
while K != 0 and i != N:
    if previous_s != S[i]:
        if previous_s == search_s:
            K -= 1
        previous_s = S[i]        
    i += 1
if K > 0:
    print(N-1)
else:
    new_S += non_search_s*(i-1)
    new_S += S[i-1:N]
    count_s = 0
    previous_s = new_S[0]
    for i in range(1,N):
        if previous_s == new_S[i]:
            count_s +=1
        else:
            previous_s = new_S[i]
    print(count_s)

Submission status: Accepted

Solution code:
N,K = map(int,input().split(' '))
S = input()
previous_idx = 0
if S[0] == 'L':
    search_s = 'R'
    non_search_s = 'L'
else:
    search_s = 'L'
    non_search_s = 'R'

flag  = False
i = 0
count_s = 0
new_S = ''
previous_s = S[0]
while K != 0 and i != N:
    if previous_s != S[i]:
        if previous_s == search_s:
            #new_S += non_search_s*count_s
            K -= 1
        #else:
            #new_S += non_search_s*count_s
        previous_s = S[i]
        #count_s = 1
        #count_s += 1
        #if i+1 == N:
        #    flag =True
            #new_S += non_search_s*count_s
        
    i += 1
if K > 0:
    print(N-1)
else:
    new_S += non_search_s*(i-1)
    if not flag:
        new_S += S[i-1:N]
    #print(new_S)
    count_s = 0
    previous_s = new_S[0]
    for i in range(1,N):
        if previous_s == new_S[i]:
            count_s +=1
        else:
            previous_s = new_S[i]
    print(count_s)

Submission status: Accepted

Solution code:
N,K =map(int,input().split())
S = input()
count = 0
last = 'N'
for x in S:
    if x == last:
        count +=1
    last = x
count += K*2
if count > N-1:
    print(N-1)
else:
    print(count)

Submission status: Accepted

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

for n in range(1, N):
    if S[n-1] == 'R' and S[n] == 'R':
        count += 1
    elif S[n-1] == 'L' and S[n] == 'L':
        count += 1

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
count=0
while 'LL'in s:
    l=len(s)
    s=s.replace('LL','L')    
    count+=l-len(s)
while 'RR'in s:
    l=len(s)
    s=s.replace('RR','R')    
    count+=l-len(s)
print(count+min(2*k,len(s)-1))

Submission status: Accepted

Solution code:
# 2019-11-18 00:38:19(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# import re
# import heapq
# import array
# from scipy.misc import comb # (default: exact=False)
# import numpy as np 

def main():
    n, k = [int(x) for x in sys.stdin.readline().split()]
    s = sys.stdin.readline().rstrip()

    happy_count = sum([0] + [1 for i in range(n-1) if s[i] == s[i+1]])
    
    happy_count += 2 * k
    ans = min(happy_count, n - 1)
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# 2019-11-18 00:38:19(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# import re
# import heapq
# import array
# from scipy.misc import comb # (default: exact=False)
# import numpy as np 

def main():
    n, k = [int(x) for x in sys.stdin.readline().split()]
    s = sys.stdin.readline().rstrip()

    happy_count = 0
    happy_count += sum(1 for i in range(n-1) if s[i] == s[i+1])
    
    happy_count += 2 * k
    ans = min(happy_count, n - 1)
    print(ans)
    
if __name__ == "__main__":
    main()