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 sys import stdin


def main():
    N, K = [int(x) for x in stdin.readline().rstrip().split()]
    S = stdin.readline().rstrip()
    score = 0
    for i, c in enumerate(S[:-1]):
        if c == S[i + 1]:
            score += 1
    print(min(N - 1, score + 2 * K))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    N, K = map(int, input().split())
    S = input()

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

    res = min([res + 2 * K, N - 1])
    print(res)

Submission status: Accepted

Solution code:
def d_face_produces_unhappiness():
    N, K = [int(i) for i in input().split()]
    S = input()

    # 初期状態で幸福な人数 + 1回の操作で高々2人増やせる。ただしN-1人まで
    score_first = len([1 for i in range(N - 1) if S[i] == S[i + 1]])
    return min(score_first + 2 * K, N - 1)

print(d_face_produces_unhappiness())

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import copy
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()

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

Submission status: Accepted

Solution code:
# sys.stdin.readline
import sys

input = sys.stdin.readline


class AtCoder:
    def main(self):
        N, K = map(int, input().split())
        S = input().rstrip()

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

# Run main
if __name__ == '__main__':
    AtCoder().main()

Submission status: Accepted

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

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

for f in range(k):
    if n-1 == count:
        break
    elif RL < 2:
        count = count + 1
        break
    else:
        count = count + 2
        RL = RL - 2

print(count)

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    N, K = map(int, input().split())
    S = input()

    # まず最初の幸福な人数を数え、文字列を圧縮する
    res = 0
    for i in range(N-1):
        if S[i+1] == S[i]:
            res += 1

    res = min([res + 2 * K, N - 1])
    print(res)

Submission status: Accepted

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

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

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

Submission status: Accepted

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

# 文字列sの幸福度をカウントする関数
def count_happy(s):
    count = 0
    for i in range(1,len(s)-1):
        if s[i]==s[i-1]:
            count += 1
    return count

# print(count_happy(s))
ans = count_happy(s) + 2*k
ans_final = min(n-1,ans)
print(ans_final)

Submission status: Accepted

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

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

Submission status: Accepted

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

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

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

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 += k*2
if ans > n-1:
    ans = n-1
    
print(ans)

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:

import sys
input=sys.stdin.readline
n,k = map(int,input().split())
s = input()
res=0
for i in range(n-1):
    if s[i] == s[i+1]:res+=1
print(min(n-1,res+2*k))

Submission status: Accepted

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

for i in range(n-1):
    if happy_lines[i] == happy_lines[i+1]:
        count += 1

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

Submission status: Accepted

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

ch_list=[]
for i in range(1,N):
  if S[i-1]!=S[i]:
    ch_list.append(i)
#print(ch_list)
len_ch=len(ch_list)

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
t=s[0]
c=[-1,1][s[0]=="R"]
d=[]

for i in s[1:]:
    if t!=i:
        d.append(c)
        c=0
    t=i
    c+=[-1,1][i=="R"]
d.append(c)
c=len(d)
for i in range(k):
    if i*2+1>=c: break
    d[i*2+1]*=-1
chk=0
ans=0
for i in d:
    if (i>0 and chk>0) or (i<0 and chk<0):
        chk+=i
    else:
        if chk!=0: ans+=abs(chk)-1
        chk=i
print(ans+(abs(chk)-1))

Submission status: Accepted

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

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

for k in range(K):
  i = 2 * k + 1
  if i >= len(l):
    break
  if S[l[i][0]] == "L":
    S[l[i][0] : l[i][1] + 1] = "R" * l[i][2]
  else:
    S[l[i][0] : l[i][1] + 1] = "L" * l[i][2]

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

print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

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

s = input()

cnt = 0
f = s[0]
for i in range(1, n):
    l = s[i]
    if l == f:
        continue
    else:
        f = l
        cnt +=1

minus = max(cnt-2*k, 0)

ans = n - 1 - minus

print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
t=s[0]
c=[-1,1][s[0]=="R"]
d=[]

for i in range(1,n):
    if t!=s[i]:
        d.append(c)
        c=0
    t=s[i]
    c+=[-1,1][s[i]=="R"]
d.append(c)
c=len(d)
for i in range(k):
    if i*2+1>=c: break
    d[i*2+1]*=-1
chk=0
ans=0
for i in d:
    if (i>0 and chk>0) or (i<0 and chk<0):
        chk+=i
    else:
        if chk!=0: ans+=abs(chk)-1
        chk=i

print(ans+(abs(chk)-1))

Submission status: Accepted

Solution code:
(N, K) = (int(i) for i in input().split())
s = input()

count = 0
for i in range(1, N):
    if s[i-1:i+1] == 'LR' or s[i-1:i+1] == 'RL':
        count += 1

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

Submission status: Accepted

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


hukou = 0
for i in range(N):
    if S[i] == 'L':
        if i == 0 or S[i-1] == 'R':
            hukou += 1
            
    if S[i] == 'R':
        if i == N-1 or S[i+1] == 'L':
            hukou += 1

hukou -= 1
if hukou <= K*2:
    print(N-1)
else:
    print(N-hukou+K*2-1)

Submission status: Accepted

Solution code:
from collections import Counter

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

v = Counter(S)
d, _ = v.most_common()[0]


def search(c1, c2):
    ret1 = 0
    ret2 = 0

    cnt = 0
    for i in range(1, N):
        if S[i - 1] == c1 and S[i] == c2:
            ret1 += 1
        elif S[i - 1] == c2 and S[i] == c1:
            ret2 += 1

        if S[i - 1] == S[i]:
            cnt += 1

    return ret1, ret2, cnt


if d == 'R':
    r1, r2, cnt = search('L', 'R')
else:
    r1, r2, cnt = search('R', 'L')

if r1 == 0 or r2 == 0:
    print(N - 1)
else:
    ret = cnt + min(min(r1, r2), K) * 2
    if K - min(r1, r2) > 0:
        ret += abs(r1 - r2)

    print(ret)

Submission status: Accepted

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

ans = N-1

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

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

Submission status: Accepted

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

cnt = 0

if len(S) == 1:
    print(0)
    exit()

if S[0] == 'R' and S[1] == 'R':
    cnt += 1

if S[-1] == 'L' and S[-2] == 'L':
    cnt += 1


for i in range(1, n - 1):
    lft = S[i - 1]
    rgt = S[i + 1]
    me = S[i]
    if lft == me == 'L':
        cnt += 1

    if rgt == me == 'R':
        cnt += 1

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

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def main():
    N, K = map(int, input().split())
    s = input().strip() + "K"
    ans = 0
    pre = s[0]
    for i in range(1, N):
        if pre == s[i]:
            ans += 1
        else:
            pre = s[i]
    print(min(N-1, ans + K*2))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
Ss = input()
 
num = Ss.count('RL')*2
if list(Ss)[-1]=='R':
  num += 1
if list(Ss)[0]=='L':
  num += 1
ans = N - max(1, num-2*K)
print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc140/tasks/abc140_d
# D - Face Produces Unhappiness
import bisect
N, K = list(map(int, input().split()))
S = input().split()[0]

p = 0
lr_index_list = []
rl_index_list = []
for i in range(1, N):
    if S[i] == S[i-1]:
        p += 1
    if S[i-1] + S[i] == 'LR':
        lr_index_list.append(i-1)
    if S[i-1] + S[i] == 'RL':
        rl_index_list.append(i-1)

n_lr = len(lr_index_list)
n_rl = len(rl_index_list)

if n_lr == 0 and n_rl == 0:
    pass
elif n_lr == 1 and n_rl == 0:
    if lr_index_list[0] != 0 and lr_index_list[0] != N - 2:
        # LLLLLRRRRR 系
        p = N - 1
elif n_lr == 0 and n_rl == 1:
    if rl_index_list[0] != 0 and rl_index_list[0] != N - 2:
        # RRRRRLLLLL 系
        p = N - 1
else:
    kouho_n = min(n_lr, n_rl)
    # 少ない方を基準で探す
    if kouho_n == n_lr:
        x_list = lr_index_list
        org_x_list = x_list[:]
        y_list = rl_index_list
        org_y_list = y_list[:]
    else:
        x_list = rl_index_list
        org_x_list = x_list[:]
        y_list = lr_index_list
        org_y_list = y_list[:]
    c = 0
    for x in org_x_list:
        y_index = bisect.bisect_left(y_list, x)
        is_ok = False
        # 1個右隣をチェック
        if y_index != len(y_list):
            if abs(y_list[y_index] - x) >= 2:
                is_ok = True
                y_list.remove(y_list[y_index])
                x_list.remove(x)
        # 1個左隣をチェック
        if is_ok == False and y_index != 0:
            if abs(y_list[y_index-1] - x) >= 2:  # TODO
                is_ok = True
                y_list.remove(y_list[y_index-1])
                x_list.remove(x)
        # 2個右隣があるかどうかをチェック
        if is_ok == False and y_index + 1 < len(y_list):
            is_ok = True
            y_list.remove(y_list[y_index+1])
            x_list.remove(x)
        # 2個左隣があるかどうかをチェック
        if is_ok == False and y_index - 2 >= 0:  # TODO
            is_ok = True
            y_list.remove(y_list[y_index-2])
            x_list.remove(x)
        if is_ok:
            c += 1
        if c >= K:
            break

    p += min(c, K) * 2

    w_list = x_list + y_list
    if 0 in w_list:
        w_list.remove(0)
    if N - 1 in w_list:
        w_list.remove(N-1)

    if K - c >= 1 and w_list:
        p += 1

ans = p
print(ans)

Submission status: Accepted

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

counts = []

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

Submission status: Accepted

Solution code:
b = list(map(int,input().split()))
n = input()
c=0
for i in range(b[0]-1):
  if n[i]==n[i+1]:
    c+=1
  else:
    c=c   

print(min(b[0]-1,c+2*b[1]))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
x = 0
y = 0
unhappy = 0
for i in range(n):
    if s[i-1:i+1] == "LR":
            x += 1
    elif s[i-1:i+1] == "RL":
            y += 1
unhappy = x + y
if k > min(x,y):
    unhappy = 0
else:
    unhappy -= 2 * k
print(n - 1 - unhappy)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
counter = 0
RL = 0
RL_L = 0
RL_R = 0

if S[0] == 'L':
    RL_L += 1

if S[N-1] == 'R':
    RL_R += 1

for i in range(N-1):
    if S[i:i+2] == 'RL':
        counter += 1

if (counter - K) >= 0:
    counter -= K
    K = 0
else:
    K -= counter
    counter = 0
    RL = 0

if RL_L == 1 and K > 0:
    RL_L -= 1
    K -= 1

if RL_R == 1 and K > 0:
    RL_R -= 1
    K -= 1

ans = N - (counter*2 + RL_L + RL_R)

print(min(ans, N-1))

Submission status: Accepted

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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

# 初期状態でOKなものを数えておく
is_ok = [0] * N
for i in range(N):
    if S[i] == 'L':
        if i != 0 and S[i-1] == 'L':
            is_ok[i] = 1
    else:
        if i != N-1 and S[i+1] == 'R':
            is_ok[i] = 1

# LかRが連続する区間毎にまとめる
A = []
st = 0
for i in range(1, N):
    if S[i] != S[i-1]:
        A.append((st, i, S[i-1]))
        st = i
A.append((st, N, S[-1]))

# その区間を逆にしたらいくつ増やせるかを格納するLR
LR = {'L': [], 'R': []}
# ずっとLかRだけなら何も増やせない
if len(A) >= 2:
    for st, end, d in A:
        # 先頭と末尾だけは+1
        if st == 0 or end == N:
            LR[d].append(1)
        # 他の場所は+2できる
        else:
            LR[d].append(2)

LR['L'].sort(reverse=True)
LR['R'].sort(reverse=True)
# 大きい値から貪欲にK回変えてみて、Lを変えるとRを変えるの良い方
ans = sum(is_ok) + max(sum(LR['L'][:K]), sum(LR['R'][:K]))
print(ans)

Submission status: Accepted

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

s = input().strip()

first_is_L = s[0] == 'L'
last_is_R  = s[-1] == 'R'
cnt = s.count("RL")

X = cnt
Y = first_is_L + last_is_R


turn = min(k, cnt)
rest_X = cnt - min(k, cnt)
rest_k = k - turn


rest_Y = Y - min(rest_k, Y)

ans = len(s) - rest_X * 2 - rest_Y
print(min(ans, len(s)-1))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
RLcnt = s.count("RL")
cnt = 0 + (s[0] == "L") + (s[-1] == "R")

res = RLcnt - k

if res >= 0:
  print(n - (res * 2 + cnt))
else:
  print(n - 1)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
t=s[0]
c=[-1,1][s[0]=="R"]
d=[0]

for i in range(1,n):
    if t!=s[i]:
        d.append(c)
        c=0
    t=s[i]
    c+=[-1,1][s[i]=="R"]
d.append(c)
c=len(d)

if c>2:
    for i in range(1,k+1):
        if i*2>=c: break
        d[i*2]*=-1
chk=0
ans=0
for i in d:
    if (i>0 and chk>0) or (i<0 and chk<0):
        chk+=i
    else:
        if chk!=0: ans+=abs(chk)-1
        chk=i

print(ans+(abs(chk)-1))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
#print(s)
t=s[0]
c=[-1,1][s[0]=="R"]
d=[0]

for i in range(1,n):
    if t!=s[i]:
        d.append(c)
        c=0
    t=s[i]
    c+=[-1,1][s[i]=="R"]
d.append(c)
c=len(d)

#print(c,d)
if c>2:
    for i in range(1,k+1):
        if i*2>=c: break
        d[i*2]*=-1
#print(d)
"""
p=[-1,-1]
for i in range(1,c-1):
    tmp=(abs(d[i-1])+abs(d[i])+abs(d[i+1]))
    if tmp>p[0]:
        p[0]=tmp
        p[1]=i
i=p[1]
for j in range(k):
    if i+j*2>=c: break
    d[i+j*2]*=-1
"""
chk=0
ans=0
for i in d:
    if (i>0 and chk>0) or (i<0 and chk<0):
        chk+=i
    else:
        if chk!=0: ans+=abs(chk)-1
        chk=i

print(ans+(abs(chk)-1))

Submission status: Accepted

Solution code:
import re

def nchars(s, n):
    """文字列 s に、同じ文字が n 個以上連続している部分文字列を見つける
    """
    assert n > 0
    reg = re.compile("(.)\\1{%d,}" % (n - 1))  # カンマを取ると n 個ちょうどになる
    while True:
        m = reg.search(s)
        if not m:
            break
        yield m.group(0)
        s = s[m.end():]


def main():
    [N, K] = [int(number) for number in input().split()]
    S = input()
    s = [len(rl) for rl in list(nchars(S,1))]
    happy = sum(s)-len(s) + K * 2
    if happy >= N:
        print(N-1)
    else:
        print(happy)


    """
    i = K
    while (i > 0):
        len_s = len(s)
        if len_s < 3:
            break
        if i == K:
            three_range_arr = [s[j] + s[j+1] + s[j+2] for j in range(len_s) if j < len_s-2]
            max_tra = max(three_range_arr)
            index = three_range_arr.index(max_tra)
        else:
            index = s.index(max(s))
            if index == 0:
                max_tra = s[index]+s[index+1]+s[index+2]
            elif index == len_s - 1:
                max_tra = s[index-2] + s[index-1] + s[index]
                index -= 2
            else:
                if index == 1:
                    maxs = [s[index-1] + s[index] + s[index+1], s[index]+s[index+1]+s[index+2]]
                elif index == len_s-2:
                    maxs = [s[index-2] + s[index-1] + s[index], s[index-1] + s[index] + s[index+1]]
                else:
                    maxs = [s[index-2] + s[index-1] + s[index], s[index-1] + s[index] + s[index+1], s[index]+s[index+1]+s[index+2]]
                max_tra = max(maxs)
                offset = maxs.index(maxs) - 2
                if index == 1:
                    offset += 1
                index += offset
        if index == 0:
            ss = [max_tra]
            ss.extend(s[index+3:len_s])
        elif index == len_s - 3:
            ss = s[0:index-1]
            ss.extend([max_tra])
        else:
            ss = s[0:index-1]
            ss.extend([max_tra])
            ss.extend(s[index+3:len_s])
        #s = s[0:index-2].append(max_tra)#.extend(s[index+1, len_s-1])
        i-=1
        s=ss

    if i > 0:
        print(N-1)
    else:
        print(sum(s)-len(s))
    """


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
t = tuple(map(lambda x: 1 if x == 'L' else 0, s))

x = t[0]
region_count = 1
for tt in t:
    if tt ^ x == 1:
        region_count += 1
        x ^= 1

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

Submission status: Accepted

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

Submission status: Accepted

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

if S[0] == 'R':
    tmp = 'RL'
else:
    tmp = 'LR'
cnt = 0
ans = 0
for i in range(len(S) - 1):
    if S[i] == S[i + 1]:
        ans += 1
    if S[i:i + 2] == tmp:
        cnt += 1

if cnt > M:
    ans += 2 * M
else:
    ans += 2 * cnt

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

Submission status: Accepted

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

lr = 0
rl = 0
for i in range(1, n):
    if s[i-1] == "L" and s[i] == "R":
        lr += 1
    if s[i-1] == "R" and s[i] == "L":
        rl += 1
ans = n - (lr + rl + 1) + (2 * min(min(lr, rl), k))

if k > min(lr, rl):
    if lr > rl and (s[0] == "L" or s[-1] == "R"):
        ans += 1
    if lr < rl and (s[0] == "R" or s[-1] == "L"):
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
LR = {'L':'R', 'R':'L'}
indices = []
T = []
for i in range(N-1):
    s = S[i:i+2]
    base = S[i]+LR[S[i]]
    if s == base:
        indices.append(S[i:].index(base)+i+1)
i = 0
for j in indices:
    T.append(S[i:j])
    i = j
T.append(S[i:])
cnt = 0
for i, t in enumerate(T):
    if i % 2 == 0:
        continue
    T[i] = LR[t[0]]*len(t)
    cnt += 1
    if cnt == K:
        break

T = ''.join(T)
ans = 0
for i in range(N-1):
    t = T[i:i+2]
    if t in ['RR', 'LL']:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
S=input()
c=S[0]
ans=0
for x in S[1::]:
    if x!=c:
        c=x
    else:
        ans+=1
print(min(ans+2*K,N-1))

Submission status: Accepted

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

P=len(S)-1-gap
if(gap==0):
    print(P)
    exit()

for i in range(K):
    if(gap>1):
        P+=2
    else:
        P+=1
        break
    gap-=2
    if(gap==0):
        break

print(P)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = list(input())
Y = 0
if N == 1:
    print(0)
    exit(0)

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

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

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

Submission status: Accepted

Solution code:
n,k = map(int, input().split()[:2])
s = input()
 
num = s.count('LR') + s.count('RL') + 1
 
ans = n - max(1, num-2*k)
print(ans)

Submission status: Accepted

Solution code:
tmp = list(map(int,(input().split())))
n   = tmp[0]
k   = tmp[1]
s   = input()

bound = 0
cnt = 0
score = 0
for i in range(1,n):
  if s[i] != s[i-1]:
    bound += 1
    score += cnt
    cnt = 0
  else:
    cnt += 1
    if i == n-1:
      score += cnt

if bound <= k*2:
  score = n - 1
else:
  score += k * 2

print (score)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
Rs = []
now = S[0]
count = -1
 
for i in range(N):
    if S[i] == now:
        count += 1
    else:
        Rs.append(count)
        count = 0
        now = S[i]
Rs.append(count)
ans = 0

if S[0] == S[N-1]:
    if K >= (len(Rs)-1) // 2:
        ans = N-1
    else:
        ans = sum(Rs) + 2 * K
else:
    if K >= len(Rs) // 2:
        ans = N-1
    else:
        ans = sum(Rs) + 2 * K
  
print(ans)

Submission status: Accepted

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

    unhappy = 0
    if s[0] == 'L':
        unhappy += 1

    if s[-1] == 'R':
        unhappy += 1

    for i in range(n-1):
        if s[i:i+2] == 'RL':
            unhappy += 2

    print(min(len(s)-1, len(s)-(unhappy-2*k)))

resolve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC140 D

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

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

Submission status: Accepted

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

old='X'
count=0
for i,s in enumerate(S):
    if s==old:
        count+=1

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

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
S=input()
SC=[]
c=1
for i in range(N-1):
    if S[i]!=S[i+1]:
        SC.append(c)
        c=1
    else:
        c+=1

SC.append(c)

L=len(SC)

if L<=K+1:
    print(N-1)

else:
    ans=sum(SC[0:2*K+1])-1
    for i in range(2*K+1,L):
        if SC[i]>1:
            ans+=SC[i]-1
    print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
prev = 'e'
flag = 0

count = 0
        
for i in range(n):
    if s[i] == 'L':
        if prev == 'R':
            if k == 0:
                pass
            elif flag == 0:
                flag = 1
            else:
                count += 2
                k -= 1
                flag = 0
        elif prev == 'L':
            count += 1
    else:
        if prev == 'L':
            if k == 0:
                pass
            elif flag == 0:
                flag = 1
            else:
                count += 2
                k -= 1
                flag = 0
        elif prev == 'R':
            count += 1
    if i == n - 1:
        if flag == 1:
            count += 1
    prev = s[i]
    
print(count)

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    S = input()
    ans = 0
    prev_c = "_"
    for c in S:
        if prev_c == c:
            ans += 1
        prev_c = c
    k = N-1-ans
    ans += min(K*2, k)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys
def main():
    input = sys.stdin.readline
    NK = list(map(int, input().split()))
    N = NK[0]
    K = NK[1]
    S = input()
    firsth = 0
    for i in range(N):
      if i != N - 1:
        if S[i] == S[i+1]:
          firsth += 1
    ans = min([firsth + 2 * K, N - 1])
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

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

conti = 0

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

Submission status: Accepted

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

if N == 1:
    print(0)
else:
    i = 1
    count = 0
    while i < N:
        if S[i] == S[i - 1]:
            count += 1
        i += 1
    print(min((count + 2 * K), N - 1))

Submission status: Accepted

Solution code:
#import numpy as np

N, K = map(int, input().split())
s = input()
if len(s) >= 2 and s[0] == "R" and s[-1] == "R":
    s = s.replace("L", "#").replace("R", "L").replace("#", "R")

s = list(s) 

done = 0

out = 0

#gid_list = []
#gnum_list = []
#gkukan_list = []
#
#cur_gid = 0
#cur_gnum = 0
#cur_gstart = 0

for i in range(N):
    cur_c = s[i]
    
    if s[i] == "L" and i >= 1 and s[i-1] == "L":
        out += 1
    elif s[i] == "R" and i <= N-2 and s[i+1] == "R":
        out += 1

#    if i >= 1:
#        if cur_c != before_c:
#            cur_gend =i-1
#            cur_gkukan = [cur_gstart, cur_gend]
#            gkukan_list.append(cur_gkukan)
#            cur_gstart = i
#
#            gnum_list.append(cur_gnum)
#            cur_gnum = 0
#
#            cur_gid += 1
#    
#    cur_gnum += 1
#    gid_list.append(cur_gid)
#
#    before_c = cur_c
#
#cur_gend =N-1
#cur_gkukan = [cur_gstart, cur_gend]
#gkukan_list.append(cur_gkukan)
#gnum_list.append(cur_gnum)
#len_g = len(gnum_list)



#for i in range(N):
#    if done < K:
#        if 1 <= i <= N-2:
#            # L(RL) -> LLL
#            if s[i-1] == "L" and s[i] == "R" and s[i+1] == "L":
#                s[i] = "L"
#                out += 2
#                done += 1
#    else:
#        break

#print("current", out, done, s)
i = 0
while i < N:
    if done < K:
        if 0 <= i <= N-2:
           # L(RL) -> LLL
            if s[i] == "L" and s[i+1] == "R":
                start_i = i+1
                i += 1

                found = True
                while s[i] == "R":
                    i += 1
                    if i >= N:
                        found = False
                        break
               
                # s[i] == "L" made

                if found:
                    end_i = i-1
                else:
                    #end_i = N-1
                    break
                
                for j in range(start_i, end_i+1):
                    s[j] = "L"

                #print("found", found, start_i, end_i)
                if found:
                    out += 2
                #else:
                #    out += 1
                #    break

                done += 1

                i -= 1 # s[i] == "R" ni modosu
        else:
            pass
            #print("false", i)

        i += 1
    else:
        break


#for i in range(N):
#    if done < K:
#        if 1 <= i <= N-2:
#            # R(LR) -> RRR
#            if s[i-1] == "R" and s[i] == "L" and s[i+1] == "R":
#                s[i] = "R"
#                out += 2
#                done += 1
#    else:
#        break

#for i in range(N-1):
#    if done < K:
#        if s[i] == "R" and s[i+1] == "L":
#            s[i] = "L"
#            out += 1
#            done += 1
#    else:
#        break



i = 0
if done < K:
    if s[0] == "R":
        start_i = 0

        found = True
        while s[i] == "R":
            end_i = i
            i += 1
            if i >= N:
                found = False
                break

        if found:
            for j in range(start_i, end_i+1):
                s[j] = "L"
            out += 1
            #print("test0")
            
        done += 1


i = N-1
if done < K:
    if s[i] == "R":
        #print("test3", out)
        end_i = i

        found = True
        while s[i] == "R":
            start_i = i
            i -= 1
            if i <= -1:
                found = False
                break

        if found:
            #start_i = i-1
            for j in range(start_i, end_i+1):
                s[j] = "L"
            out += 1
            #print("test0")
            
        done += 1

print(out)