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:
n, k = [int(v) for v in input().split()]
s = input()

x = 0
y = 0
if s[0] == 'L':
    y += 1
if s[-1] == 'R':
    y += 1

ans = 0
for i in range(n-1):
    ad = s[i:i+2]
    if ad == 'RL':
        x += 1
    if ad == 'LL' or ad == 'RR':
        ans += 1

while k > 0 and x > 1:
    ans += 2
    x -= 1
    k -= 1
if k > 0 and x == 1:
    if y == 0:
        ans += 1
    else:
        ans += 2
    k -= 1
if k > 0 and y == 2:
    ans += 1

print(ans)

Submission status: Accepted

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

unhapiness = 0
div = deque([])
left = "R"
right = "L"
cntr = 0
s = s + "L"
for si in s:
    right = si
    if (left == "R") & (right == "L"):
        if 0 < cntr < n:
            unhapiness += 2
            div.append(cntr)
        else:
            unhapiness += 1
            div.appendleft(cntr)

    left = si
    cntr +=1

for i in range(k):
    p = div.pop()
    if 0 < p < n:
        unhapiness -= 2
    else:
        unhapiness -= 1
    if len(div) < 1:
        unhapiness += 1
        break
print(n-unhapiness)

Submission status: Accepted

Solution code:
## 幸福度が変わるかどうかは操作Kによって変更されたl, r番目の人間だけなので、
## 左右l,r番目の人間が幸福であるかどうかを見てゆく
## for(n)回のループでまず「既に 1 + x, 任意の r が幸福であるかどうか」を確認して、
## 幸福度2, 1の順でそのl,rをK回覚える
n, k = map(int, input().split())
humans = list(input())
k_count = 0
last_r = n ## 最後に操作したr(番目)
dev_null = 0

## ポイントを計算
happy_point = 0
for x in range(n - 1):
  if humans[x] == humans[x+1]:
    happy_point += 1
print(min(n-1,happy_point+2*k))

Submission status: Accepted

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

happy = 0
for n in range(N - 1):
     if B[n] == B[n + 1]:
            happy += 1

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

Submission status: Accepted

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

init_score = 0
pre_s = 0
for s in S:
    if pre_s == s:
        init_score += 1
    pre_s = s

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=input()
ans=0
if s[0]=="L" and s[n-1]=="R":
    c=s.count("LR")
    if k>=c:
        ans=n-1
    elif k==c-1:
        ans=n-2
    else:
        ans=n-2-2*(c-1)+2*k
elif s[0]=="L" and s[n-1]=="L":
    c=s.count("LR")
    if k>=c:
        ans=n-1
    else:
        ans=n-1-2*c+2*k
elif s[0]=="R" and s[n-1]=="R":
    c=s.count("LR")
    if k>=c:
        ans=n-1
    else:
        ans=n-1-2*c+2*k
else:
    c=s.count("RL")
    ans=n-c*2
    if k>=c:
        ans=n-1
    else:
        ans+=2*k
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from math import ceil
count=0
n,k=map(int,input().split())
s=list(input())
for i in range(n-1):
    if s[i]!=s[i+1]:
        count+=1
kaisu=ceil(count/2)
if k>=kaisu:
    print(n-1)
else:
    print(n-1-2*(kaisu-k)+(count%2))

Submission status: Accepted

Solution code:
N , K = map(int,input().split())
ans = 0
S = input()
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:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n = I()
    print(n**3)
    return

#B
def B():
    n = I()
    a = LI()
    b = LI()
    c = LI()
    ans = sum(b)
    for i in range(n-1):
        x = a[i]
        y = a[i+1]
        if y == x+1:
            ans += c[x-1]
    print(ans)
    return

#C
def C():
    n = I()
    b = LI()
    b.append(float("inf"))
    a = [min(b[i],b[i-1]) for i in range(n)]
    print(sum(a))
    return

#D
def D():
    n,k = LI()
    a = S()
    ans = 0
    for i in range(n-1):
        if a[i] == a[i+1]:
            ans += 1
    print(min(n-1,ans+2*k))        
    return

#E
def E():
    def add(i):
        while i <= n:
            bit[i] += 1
            i += i&-i

    def sum(i):
        res = 0
        while i > 0:
            res += bit[i]
            i -= i&-i
        return res

    n = I()
    p = LI()
    r = [0]*n
    bit = [0]*(n+1)
    for i in range(n)[::-1]:
        r[i] = (n-i-1)-sum(p[i])
        add(p[i])
    print(r)
    l = [0]*n
    bit = [0]*(n+1)
    for i in range(n):
        l[i] = i-sum(p[i])
        add(p[i])
    print(l)

    return

#F
def F():
    n = I()
    s = LI()
    s.sort()
    s = s[::-1]
    if s[0] == s[1]:
        print("No")
        return
    a = [s[0]]
    j = 1
    s.append(0)
    q = deque()
    for _ in range(n):
        for i in range(1<<_):
            if a[i] > s[j]:
                a.append(s[j])
                j += 1
            else:
                q.append(a[i])
    print(a)
    return

#Solve
if __name__ == "__main__":
    D()

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=list(map(lambda x:0 if x=='R' else 1,input()))
c=0
a=s[0]
b=a^1
for i in range(n-1):
    if s[i:i+2]==[b,a]:
        c+=1
        s[i]=a
    elif s[i]==b:
        s[i]=a
    if c==k:
        ans=0
        for i in range(n-1):
            if s[i]==s[i+1]:
                ans+=1
        print(ans)
        break
else:
    print(n-1)

Submission status: Accepted

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

tmp=[]
l=1
for i in range(n):
    if s[i]==s[i+1]:
        l+=1
    else:
        tmp.append(l)
        l=1

RLs=max(1, len(tmp)-2*k)

ans=n-RLs
print(ans)

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import re

n, k = map(int, input().split())
str = input()

result = n-1

pattern = re.compile("RL")
X = len(pattern.findall(str))

if (str[0] == 'R') ^ (str[-1] == 'L'):
    Y = 0
else:
    if (str[0] == 'R') and (str[-1] == 'L'):
         X -= 1
    Y = 1

if k < X+Y:
    result -= Y + 2 * (X-k)

print(result)

Submission status: Accepted

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

i = 1
c = 0
cc = 0
while i < n:
	if s[i] == s[i - 1]:
		c += 1
	else:
		cc += 1

	i += 1

print(c + min(2 * k, cc))

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:
n, k = map(int, input().split())
s = input()
happy = 0

if n == 1:
  print(0)
elif n == 2:
  print(1)
else:
  for i in range(n-1):
    if s[i] == s[i+1]:
      happy += 1
  print(min(happy+2*k, n-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

if count < k*2:
    print(n-1)
else:
    print(n-count-1+k*2)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

MOD = 10 ** 9 + 7

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

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

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

print(ans)

Submission status: Accepted

Solution code:
import sys

#+++++
		
def main():
	n, k = map(int, input().split())
	sl = input()
	ss=0
	for cp, cn in zip(sl, sl[1:]):
		#print(cp,cn)
		if cp == cn and cp == 'L':
			ss+=1
			
	for cp, cn in zip(sl, sl[1:]):
		#print(cp,cn)
		if cp == cn and cp == 'R':
			ss+=1	
			
	nh=n-ss
	#print(nh,k,ss)
	ss += min(nh-1,k*2)
	
	
	print(ss)
	
	
#+++++


if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
## debug用


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

def count(s):
    count = 0
    s = 'R' + s +'L'
    for i in range(1, n+1):
        if s[i] == 'R':
            if s[i+1] == 'R':
                count += 1
        else:
            if s[i-1] == 'L':
                count += 1
    return count

# 変換後の文字
if s[0] == 'R':
    c_l = 'R'
else:
    c_l = 'L'

# 連続のリストを作る

s_list = []
counter = 1
for i in range(n):
    
    s_check = s + 'E'
    if s_check[i] == s_check[i+1]:
        counter += 1
    else:
        s_list.append(s[i]*counter)
        counter = 1

# 
        
if k <= len(s_list)//2:
    for i in range(1,k+1):
        num = len(s_list[i*2-1])        
        s_list[i*2-1] = c_l*num
    
    s_ans = ''.join(s_list)
    ans = count(s_ans)

else:
    ans = n-1
             
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
l = []
flg = (0 if s[0] == 'L' else 1)
cnt = 0
for c in s:
    if flg == 1 and c == 'L':
        flg = 0
        l.append(cnt)
        cnt = 0
    elif flg == 0 and c == 'R':
        flg = 1
        l.append(cnt)
        cnt = 0
    cnt += 1
l.append(cnt)
y = (0 if len(l) % 2 else 1)
x = len(l) // 2 - y
if x + y <= k:
    ans1 = x * 2 + y
elif x <= k:
    ans1 = x * 2 + (k - x)
else:
    ans1 = k * 2
ans1 += sum(l) - len(l)
y = (2 if len(l) % 2 else 1)
x = len(l) // 2 + (1 if len(l) % 2 else 0) - y
if x + y <= k:
    ans2 = x * 2 + y
elif x <= k:
    ans2 = x * 2 + (k - x)
else:
    ans2 = k * 2
ans2 += sum(l) - len(l)

print(max(ans1, ans2))

Submission status: Accepted

Solution code:
from sys import stdin

wds = stdin.readline().split()
N = int(wds[0])
K = int(wds[1])
S = stdin.readline().strip()

cnt_eq = 0
for i in range(len(S)-1):
    if S[i] == S[i+1]: cnt_eq += 1
    pass
cnt_ne = len(S)-1 - cnt_eq
ret = cnt_eq + min(cnt_ne, K * 2)

print(ret)

Submission status: Accepted

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

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

Submission status: Accepted

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

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

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

Submission status: Accepted

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

happiness=0
for c,d in zip(s,s[1:]):
  if c == d:
    happiness +=1
    
ans=min(n-1,happiness+2*k)
print(ans)

Submission status: Accepted

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

flag = True
ans = 0
for i in range(1, N):
    if S[i] == S[i-1]:
        ans += 1
    if K != 0:
        if flag:
            if S[i-1] != S[i]:
                flag = False
                ans += 1
        else:
            if S[i-1] != S[i]:
                flag = True
                ans += 1
                K -= 1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys

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

def main():
  n, k = na()
  s = ns()

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

Submission status: Accepted

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

LR = 0
RL = 0
happy = 0
for i in range(N-1):
	if S[i:i+2] == "RL":
		RL += 1
	elif S[i: i+2] == "LR":
		LR += 1
	elif S[i] == S[i+1]:
		happy += 1

if K <= min(RL, LR):
	print(happy + 2 * K)
else:
	print(N - 1)

Submission status: Accepted

Solution code:
import re

n, k = map(int, input().split())
str = input()

pattern = re.compile("RL")
X = len(pattern.findall(str))
result = n - X * 2

if str[0] == 'L' and str[-1] == 'R':
    result -= 2
    Y = 1
elif str[0] == 'L' or str[-1] == 'R':
    result -= 1
    Y = 0
else:
    Y = -1
    
if k <= X:
    result += 2 * k
else:
    result += 2 * X + Y

print(result)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
ans = 0
isOdd = False
for i in range(0, n-1):
    if s[i] == s[i+1]:
        ans += 1
    else:
        isOdd = not isOdd
        if isOdd and k > 0:
            ans += 2
            k -= 1

print(min(ans, n-1))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
H = N - 1
for i in range(N - 1):
    H -= 1 if S[i:i + 2] == "RL" or S[i:i + 2] == "LR" else 0
print(min(H + K * 2, N - 1))

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))

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

def searchRL(S):
    ans = []
    for i in range(N-1):
        if S[i] == "R" and S[i+1] == "L":
            ans.append(i)
    return ans

def searchLR(S):
    ans = []
    for i in range(N-1):
        if S[i] == "L" and S[i+1] == "R":
            ans.append(i)
    return ans

def reverse(S):
    S = list(S)
    for i in range(len(S)):
        if S[i] == 'L':
            S[i] = 'R'
        if S[i] == 'R':
            S[i] = 'L'
    return ''.join(S)


def solve(S):
    if len(RL) == 0 and len(LR) == 0:
        return S, 0
    if len(RL) == 0:
        S = reverse(S[LR[0]::-1]) + S[LR[0]+1:]
        LR.pop(0)
        return S, 1
    if len(LR) == 0:
        S = reverse(S[RL[0]::-1]) + S[RL[0]+1:]
        RL.pop(0)
        return S, 1
    fir = min(LR[0], RL[0])
    sec = max(LR[0], RL[0])
    S = S[:fir+1] + reverse(S[sec:fir:-1]) + S[sec+1:]
    LR.pop(0)
    RL.pop(0)
    return S, 2

def cal(S):
    ans = 0
    for i in range(len(S)-1):
        if S[i] == S[i+1]:
            ans +=1
    return ans

RL = searchRL(S)
LR = searchLR(S)
ans = cal(S)
for i in range(K):
    S, res = solve(S)
    ans += res
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(12345678)
import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def main():
    n, k = map(int, input().split())
    s = input()

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

if __name__ == '__main__':
    main()

Submission status: Accepted

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

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

Submission status: Accepted

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

rl = 0
lr = 0

happy = 0

for i in range(len(S) - 1):
    if S[i] == S[i+1]:
        happy += 1
    if S[i] == 'R' and S[i+1] == 'L':
        rl += 1
    if S[i] == 'L' and S[i+1] == 'R':
        lr += 1


if K <= min(rl, lr):
    print(happy + 2 * K)
    exit()

print(happy + min(rl, lr) + min(max(rl,lr),K))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# https://atcoder.jp/contests/abc140/tasks/abc140_d

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

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

# 一人しか幸せにできないときがあるか?
#
# あっ...これは不要なのでは...
# 単に後述の幸せの最大値で丸めればよいのでは
# always_two_happiness = S[0] == S[-1]

# 幸せの最大値
max_happiness = N - 1

for i in range(K):
    happiness += 2

print(min(happiness, max_happiness))

Submission status: Accepted

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

#print(N,K)
#print(S)

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

if min(rl,lr)>K:
  res+=2*K
else:
  res+=min(rl,lr)+min(max(rl,lr),K)
print(res)

Submission status: Accepted

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


def solve(N: int, K: int, S: str):

    c = S.count('RL')
    
    hap = 0
    for i in range(1,N):
        if(S[i-1] == S[i]):
            hap += 1
    print(min(hap+2*K, N-1))

    return


# Generated by 1.1.5 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()
ans=0
for i in range(n-1):
	if s[i]==s[i+1]:
		ans+=1
ans+=k*2
print(min(ans,n-1))

Submission status: Accepted

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

L=[]

now=None
for i,s in enumerate(S):
	if i==0:
		now=s
		cnt=1
	elif now==s:
		cnt+=1
	elif now!=s:
		L.append([now,cnt])
		cnt=1
		now=s
else:
	L.append([now,cnt])	

l=len(L)

for i in range(1,min(K*2,l),2):
	s=L[i][0]
	if s=="L": L[i][0]="R"
	elif s=="R": L[i][0]="L"


ans=0
prev=None
for t in L:
	s=t[0]
	cnt=t[1]
	if prev is None:
		prev=s
		lcnt=cnt
	else:
		if prev==s:
			lcnt+=cnt
		elif prev!=s:
			ans+=(lcnt-1)
			lcnt=cnt
		prev=s
else:
	ans+=(lcnt-1)
	
print ans

Submission status: Accepted

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

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

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
inpl = lambda: list(map(int,input().split()))
N, K = inpl()
S = input()
loss = 0
prev = None
for s in S:
    if s != prev:
        loss += 1
    prev = s
loss -= K*2
if loss < 1:
    loss = 1
print(N-loss)

Submission status: Accepted

Solution code:

n = list(map(int, input().split()))
a = list(str(input()))

b = []
ans = 0
for i in range((len(a) - 1)):
    if a[i] != a[i+1]:
        b.append(i)
    else:
        ans += 1

c = len(b)
if n[1]*2 >= c:
    ans += c
else:
    ans += min(c, n[1]*2)

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
from bisect import *
from collections import *
from copy import deepcopy
from heapq import *
from itertools import *
from math import *
from operator import *
import numpy as np

sys.setrecursionlimit(10**8)

input = sys.stdin.readline

def main():
    """ main """
    N,K = map(int, input().split())
    S = list(input())

    cnt = 0
    prev = ''
    for s in S:
        if s == 'L' and prev == 'R' or s == 'R' and prev == 'L':
            cnt += 1
        prev = s

    unhappy_cnt = cnt + 1
    max_changable = unhappy_cnt//2
    print(min(N-1, N-unhappy_cnt+2*min(max_changable, K)))


if __name__ == '__main__':
    main()

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
       
count = max(count-k*2,0)
print(n-1-count)

Submission status: Accepted

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

flag = True
for i in range(1, N):
    if K != 0:
        if flag:
            if S[i-1] != S[i]:
                flag = False
        if not flag:
            S[i] = 'L' if S[i] == 'R' else 'R'
            if i < N - 1:
                if S[i] == S[i+1]:
                    flag = True
                    K -= 1

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

print(ans)

Submission status: Accepted

Solution code:
import sys
import math
from fractions import gcd
# import queue
# from collections import Counter
# from itertools import accumulate
# from functools import reduce

def lcm(a, b):
    return a * b // gcd(a, b)

def combination_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def permutations_count(n, r):
    return math.factorial(n) // math.factorial(n - r)

big_prime = 1000000007

"""
# 標準入力取得
## 文字列
 =  sys.stdin.readline().rstrip()
 =  list(sys.stdin.readline().rstrip())

## 数値
 =  int(sys.stdin.readline())
 =  map(int, sys.stdin.readline().split())
 =  list(map(int, sys.stdin.readline().split()))
 =  [list(map(int,list(sys.stdin.readline().split()))) for i in range(N)]
"""

N,K = map(int, sys.stdin.readline().split())
list_s = list(sys.stdin.readline().rstrip())

sum_inverse = 0
sum_happy = 0

for i in range(N-1):
    if(list_s[i] == list_s[i+1]):
        sum_happy += 1
    else:
        sum_inverse += 1


ans = min((sum_happy + K*2), (sum_happy + sum_inverse *2))

ans = min(ans, N-1)

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = list(input())
S += [0]
s = []
L_count = 1
R_count = 1
count = 0

for i in range(N):
    if S[i + 1] == S[i] and S[i] == 'L':
        L_count += 1
    elif S[i + 1] == S[i] and S[i] == 'R':
        R_count += 1
    else:
        if S[i] == 'L':
            s.append(L_count)
            L_count = 1
        else:
            s.append(R_count)
            R_count = 1

for i in s:
    if i != 1:
        count += i - 1

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

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


def solve(S, n, k):
    S = [1 if s == 'R' else -1 for s in S]

    num_hapiness = 0
    for i in range(n):
        next_idx = i + S[i]
        if next_idx < 0 or next_idx >= n:
            continue
        if S[next_idx] == S[i]:
            num_hapiness += 1
    num_unhapiness = n - num_hapiness
    num_can_change_to_hapiness = num_unhapiness - 1
    max_can_change_to_hapiness = k * 2
    actually_change_to_hapiness = min(num_can_change_to_hapiness, max_can_change_to_hapiness)

    return num_hapiness + actually_change_to_hapiness


if __name__ == '__main__':
    n, k = map(int, input().split())
    S = input().strip()

    answer = solve(S, n, k)
    print(answer)

Submission status: Accepted

Solution code:
N,K = [int(x) for x in input().split()]
S = input()
#%%
li = [1]
ans = 0
cnt = 0

for ind,s in enumerate(S[:-1]):
    if(s==S[ind+1]):
        li[-1]+=1
    else:
        li.append(1)

#%%
for ind,i in enumerate(li):
    if(ind==0):
        ans += i-1
    elif(ind<=2*K):
        ans += i
    else:
        ans += max(i-1,0)
print(ans)

Submission status: Accepted

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

first = S[0]
flg = False
for index in range(1,N):
    if S[index] == first and flg:
        flg = False
        K -= 1
    elif S[index] != first:
        S[index] = first
        flg = True
    
    if K == 0:
        break
 
count = 0
for index in range(1,N):
    if S[index] == S[index -1]:
        count += 1
    

print(count)

Submission status: Accepted

Solution code:
"""
解説AC。むずい

反転操作で変わるもの
⇨両端の関係性だけ

違う文字で囲まれていて、
連続区間で囲まれているやつらをひっくり返すと
連続個数が+2される
LRLLLRRLR ...3

LRRRRRRLR ...5
コレでもOK(違う文字で囲まれているので)
だけど、素直に連続してもじが並んでいるものの個数を数えると良いかも
LLRRRLLLR ...5

端っこだけ注意。けど、端っこ含めてひっくり返すときは+1なので、
操作の一番最後に行う
LLLLLLLLR ...7
LLLLLLLLL ...8
"""
N,K = map(int, input().split())
S = input()

prev = S[0]
from collections import defaultdict
LRs = defaultdict(list)
cnt_seq = 0
for i in range(1,N):
    if prev == S[i]:
        cnt_seq += 1
    prev = S[i]

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

Submission status: Accepted

Solution code:
#D-Face Produces Unhappiness
N, K = map(int, input().split())
S = str(input())
S_index = [S[i]+S[i+1] for i in range(0,N-1)]

count_LRorRL =0
count_LRorRL += S_index.count('LR')
count_LRorRL += S_index.count('RL')

count_LLorRR = 0
count_LLorRR += S_index.count('LL')
count_LLorRR += S_index.count('RR')

if count_LRorRL > 2*K:
    print(count_LLorRR+2*K)
else:
    print(count_LLorRR+count_LRorRL)

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:
#D-Face Produces Unhappiness
N, K = map(int, input().split())
S = str(input())

def count_LRorRL(l):
    ans = 0
    l_index = [l[i]+l[i+1] for i in range(0,N-1)]
    ans += l_index.count('LR')
    ans += l_index.count('RL')
    return ans

def count_LLorRR(l):
    ans = 0
    l_index = [l[i]+l[i+1] for i in range(0,N-1)]
    ans += l_index.count('LL')
    ans += l_index.count('RR')
    return ans
  
if count_LRorRL(S) > 2*K:
    print(count_LLorRR(S)+2*K)
else:
    print(count_LLorRR(S)+count_LRorRL(S))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
 
ans = 0
for n in range(N): 
    if n!=0 and S[n]=='L' and S[n-1]=='L':
        ans += 1
    if n!=N-1 and S[n]=='R' and S[n+1]=='R':
        ans += 1
ans = min(ans+2*K, N-1)

print(ans)

Submission status: Accepted

Solution code:
def new_list(s_list):
    s_list_new = [s_list[0]]
    for i, s in enumerate(s_list):
        if i >= 1:
            if s != s_list[i - 1]:
                s_list_new.append(s)
    return s_list_new

if __name__ == "__main__":

    count = 0
    n, k = map(int, input().split())
    stext = str(input())
    s_list = [s for s in stext]
    s_list = new_list(s_list)
    cnt_l = s_list.count('L')
    cnt_r = s_list.count('R')
    if cnt_l == cnt_r:
        if k >= cnt_l:
            count = 1
        else:
            count = 2 * (cnt_l - k)
    else:
        cnt_lr = min(cnt_l, cnt_r)
        if k >= cnt_lr:
            count = 1
        else:
            count = 2 * (cnt_lr - k) + 1
                
    print('{0}'.format(n - count))

Submission status: Accepted

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

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

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

Submission status: Accepted

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

if N == 1:
    print(0)
else:
    H = 0
    N_LR = 0
    N_RL = 0

    if S[0] == 'R' and S[1] == 'R':
        H += 1
    if S[0] == 'R' and S[1] == 'L':
        N_RL += 1
    if S[0] == 'L' and S[1] == 'R':
        N_LR += 1

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

    for i in range(1, N-1):
        if S[i] == 'L' and S[i-1] == 'L' or S[i] == 'R' and S[i+1] == 'R':
            H += 1
        if S[i] == 'R' and S[i+1] == 'L':
            N_RL += 1
        if S[i] == 'L' and S[i+1] == 'R':
            N_LR += 1

    M = min(N_RL, N_LR, K)
    H += 2 * M
    K -= M
    N_RL -= M
    N_LR -= M

    s0 = S[0]
    while K > 0 and (s0 == 'R' and N_RL > 0 or s0 == 'L' and N_LR > 0):
        if s0 == 'R' and N_RL > 0:
            H += 1
            s0 = 'L'
            N_RL -= 1
            K -=1
        elif s0 == 'L' and N_LR > 0:
            H += 1
            s0 = 'R'
            N_LR -= 1
            K -=1

    sN = S[N-1]
    while K > 0 and (sN == 'R' and N_LR > 0 or sN == 'L' and N_RL > 0):
        if sN == 'R' and N_LR > 0:
            H += 1
            sN = 'L'
            N_LR -= 1
            K -=1
        elif sN == 'L' and N_RL > 0:
            H += 1
            sN = 'R'
            N_RL -= 1
            K -=1

    print(H)