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:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

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

#B
def B():
    n = II()
    a = LI()
    b = LI()
    c = LI()
    ans = 0
    for i in range(n):
        ans += b[a[i] - 1] + (c[a[i] - 1] if i != n - 1 and a[i] + 1 == a[i + 1] else 0)
    print(ans)
    return

#C
def C():
    n = II()
    b = LI()
    ans = b[0]
    for i in range(n-1):
        if b[i] >= b[i + 1]:
            ans += b[i + 1]
        else:
            ans += b[i]
    print(ans)
    return

#D
def D():
    n, k = LI()
    s = S()
    a = []
    for i in range(n):
        if i == n - 1:
            a.append(s[i])
        elif s[i] != s[i + 1]:
            a.append(s[i])
    print(min(n - 1, n - len(a) + 2 * k))
    return

#E
def E():
    return

#F
def F():
    return


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

Submission status: Accepted

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

countR = S.count("R")
countL = S.count("L")
idx_list = []

for i in range(1, N):
    if S[i-1] != S[i]:
        idx_list.append(i)
idx_list.append(N)

i = 1
count = 0
for i in range(1, len(idx_list), 2):
    idx_start = idx_list[i - 1]
    idx_end = idx_list[i]
    
    for j in range(idx_start, idx_end):
        if S[j] == "R":
            S[j] = "L"
        else:
            S[j] = "R"    
    
    count += 1
    if count == K:
        break

ans = 0
for i in range(len(S)):
    if i == 0 and S[i] == "L":
        continue
    if i == (len(S)-1) and S[i] == "R":
        break
    
    if (S[i] == "L" and S[i-1] == "L") or (S[i] == "R" and S[i+1] == "R"):
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, k = list(map(int, input().rstrip('\n').split()))
    s = str(input().rstrip('\n'))
    c = 0
    cl = 0
    mcl = 0
    cr = 0
    mcr = 0
    for i in range(n):
        if i != 0:
            if s[i] != s[i-1]:
                c += 1
                
        if s[i] == "R":
            cr += 1
            mcl += max((cl - 1), 0)
            cl = 0
        else:
            cl += 1
            mcr += max((cr - 1), 0)
            cr = 0

        if i == n - 1:
            mcl += max((cl - 1), 0)
            mcr += max((cr - 1), 0)

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


if __name__ == '__main__':
    slove()

Submission status: Accepted

Solution code:
N,K=[int(s) for s in input().split()]
S=list(input())
a=S[0]
index=1
for i in range(K):
  while (index<N and S[index]==a) :
    index+=1
  while (index<N and S[index]!=a) :
    S[index]=a
    index+=1
#print(S,index)
###幸せな人を数える
count=0
for i in range(1,N-1):
  if S[i]=="L":
    if S[i-1]=="L":
      count+=1
  if S[i]=="R":
    if S[i+1]=="R":
      count+=1
if (S[0]=="R"and S[1]=="R"):
  count+=1
if (S[N-1]=="L"and S[N-2]=="L"):
  count+=1
if N>1:
  print(count)
else:
  print(0)

Submission status: Accepted

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

h = N
last = ''
for s in S:
  if s != last:
    h -= 1
  last = s
print(min(N-1, h+2*K))

Submission status: Accepted

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

count = 0

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

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

print(sum_happiness)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
S = input()
happiness = N-1 - S.count('LR') - S.count('RL')
print(min(N-1,happiness+2*K))

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

dif = n - 1 - same

print(same + min(k * 2, dif))

Submission status: Accepted

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

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

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

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

print(count)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

c = 0
for i in range(n):
    if s[i] == 'R' and 0 <= i + 1 < n and s[i+1] == 'R': c += 1
    if s[i] == 'L' and 0 <= i - 1 < n and s[i-1] == 'L': c += 1
ans = min(n - 1, c + 2 * k)
print(ans)

Submission status: Accepted

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

count = 0

for i in range(n):
    if s[i:i+2] == 'LL' or s[i:i+2] == 'RR':
        count += 1
    

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

Submission status: Accepted

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

def check_happiness(people):
    num_happiness = 0
    for i in range(0, len(people)-1):
        if people[i] == 'R' and people[i+1] == 'R':
            num_happiness += 1
        if people[i] == 'L' and people[i+1] == 'L':
            num_happiness += 1
    return num_happiness

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

Submission status: Accepted

Solution code:

import sys
input = sys.stdin.readline
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
# A = [ int(input()) for _ in range(N) ]
##############################

N, K = map(int, input().split())
S = list(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) )

Submission status: Accepted

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

print(happy_counter)

Submission status: Accepted

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

ans = 0
S = "x"+"".join(S)+"x"
for i in range(len(S)):
    if (S[i-1]=="L" and S[i]=="L") or (S[i]=="R" and S[i+1]=="R"): ans += 1
print(min(ans+K*2, N-1))

Submission status: Accepted

Solution code:
n,k = (int(i) for i in input().split())
s = input()
s,num = "x"+s+"x",0
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"): num+=1
print(min(num+2*k,n-1))

Submission status: Accepted

Solution code:
N, K = list(map(int,input().split()))
S = str(input())
num_L = 0
num_R = 0
tmp = ""
count = 0
for i in range(len(S)):
    if S[i] == "L":
        if tmp == "L":
            count += 1
        else:
            num_L += 1
    else:
        if tmp == "R":
            count += 1
        else:
            num_R += 1
    tmp = S[i]
if K >= min(num_L, num_R):
    ans = N - 1
else:
    ans = count + 2*K
print(ans)

Submission status: Accepted

Solution code:
# D - Face Produces Unhappiness

import sys
input = sys.stdin.readline
N, K = map(int, input().split())
S = input()

prev_c = None
score = 0
for c in S:
    if c == prev_c:
        score += 1
    prev_c = c

score += 2 * K

print(min((N - 1, score)))

Submission status: Accepted

Solution code:
#import sys
#sys.setrecursionlimit(10**6)

N, K = map(int, input().split())
S = str(input())
Scount = []
ans = int(0)
count= int(0)
max = int(0)

count +=1
for i in range(1,N):
#    print(S[i])
    if S[i]==S[i-1]:
        count +=1
        if i==N-1:
            Scount.append(count)
    else:
        Scount.append(count)
        count = int(1)
#print(Scount)

for i in Scount:
#    print(i)
    max += i
    max -= 1
#print(max)
max += K*2

ans = min(max,N-1)

print(ans)

Submission status: Accepted

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

c = 0
for i in range(n):
    if s[i] == 'L' and i > 0 and s[i-1] == 'L':
        c += 1
    if s[i] == 'R' and i < n-1 and s[i+1] == 'R':
        c += 1
print(min(c + 2* k, n-1))

Submission status: Accepted

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

ans=0
for i in range(n-1):
    if s[i]==s[i+1]:
        ans+=1
count=0        
c='Q'
for i in range(n):
    if s[i]!=c:
        count+=1
        c=s[i]
    else:
        continue
if count==2:
    print(n-1)
elif count%2==0:
    count=count//2
    print(int(ans+min(2*count-1,2*k)))

elif count%2!=0:
    count=count//2
    print(int(ans+min(2*count,2*k)))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
S = list(input())
siawase = 0
 
LRchange_count = -1#初回必ず+1されるので、初期値を-1にしておく
LRittiFlg = True
temp_char = 'temp'
#temp_renzoku = 0
 
for s in S:
    #print(s,temp_char)
    if s != temp_char:
        LRchange_count += 1
    else:
        siawase += 1
    temp_char = s
    
if S[0] == S[-1]:
    LRittiFlg = True
else:
    LRittiFlg = False
    
if K+1 >= LRchange_count:
    print(len(S)-1)
# elif K-1 == LRchange_count:
#         if LRittiFlg:
#             print(K*2 + siawase)
#         else:
#             print(K*2 + siawase - 1)
else:
    print(min(K*2 + siawase,len(S)-1))

Submission status: Accepted

Solution code:
N, K = map(lambda x:int(x), input().split())
s = input()

S = []
score = 0
for i in range(len(s)-1):
  if i == 0:
    _s = s[i]
  else:
    _s += s[i]
  if s[i] != s[i+1]:
    S.append(_s)
    _s = ''
  else:
    score += 1

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

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = list(input())
group_num = 1
tmp_char = s[0]
for index in range(1, len(s)):
    if s[index] == tmp_char:
        continue
    else:
        tmp_char = s[index]
        group_num += 1
group_num = max(1, group_num - (k-1)*2)
if group_num >= 3:
    group_num -= 2
elif group_num == 2:
    group_num = 1

happy = len(s) - group_num
print(happy)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/python3

import math
import os
import sys


DEBUG = 'DEBUG' in os.environ


def inp():
    return sys.stdin.readline().rstrip()


def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)


def solve(N, K, S):
    A = []
    i = 0
    while i < N:
        j = i
        while j < N and S[j] == S[i]:
            j += 1
        A.append(j - i)
        i = j

    assert sum(A) == N
    cur = N - len(A)
    return min(cur + 2 * K, N - 1)


def main():
    N, K = [int(e) for e in inp().split()]
    S = inp()
    print(solve(N, K, S))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    s = input()
    a = s.count("RL")  # RLの順に並んでいる箇所をカウント
    ans = 0  # 答えを初期化
    # print("a=", a)
    for i in range(n - 1):
        if s[i] == s[i + 1]:
            ans += 1  # 最初の点数をカウント
    for i in range(1, k + 1):
        # print("i=", i)
        # print("ans=", ans)
        # print("n-1-ans=", n - 1 - ans)
        if n - 1 - ans > 1:
            ans += 2
        else:
            ans += n - 1 - ans
            break
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
A = ["N"]*N
base = S[0]
cnt = 0
comp = False
i=0
while i < N:
    if not comp and S[i]!=base:
        if cnt < K:
            comp = True
            cnt+=1
    if comp and S[i]==base:
        comp = False
    if not comp:
        A[i] = S[i]
    else:
        A[i] = base
    i+=1

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

Submission status: Accepted

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

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

if lr==rl:
    if k<rl:
        ans+=(2*k)
    else:
        ans+=(2*rl)
else:
    if rl>lr:
        if k<rl:
            ans+=(2*k)
        else:
            ans+=((2*lr)+1)
    else:
        if k<lr:
            ans+=(2*k)
        else:
            ans+=((2*rl)+1)


print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
from itertools import *
import sys
import time


#################### library ####################


#################### naive ####################


#################### process ####################

def read_input():
	[N, K] = map(int, raw_input().split())
	S = raw_input().rstrip()
	return K, S


#################### main ####################

#t0 = time.clock()
K, S = read_input()
v = [ sum(1 for _ in w) for k, w in groupby(S) ]
n = v[0] - 1
for k in range(K):
	if len(v)/2 == k:
		break
	n += v[k*2+1]
	if k*2+2 < len(v):
		n += v[k*2+2]
n += sum(m-1 for m in v[K*2+1:])
print(n)

Submission status: Accepted

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

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

count_RL, count_LR = S.count("RL"), S.count("LR")


if max(count_LR, count_RL) <= K:
    print(N-1)
elif max(count_LR, count_RL) > K:
    if count_RL == count_LR:
        happy = N-1-2*(count_LR-K)
    elif not count_RL == count_LR:
        happy = N-1-2*(min(count_LR, count_RL)-K)-1
    print(happy)

Submission status: Accepted

Solution code:
import math
N, K = map(int, input().split())
S = list(input())
ans = [0]*(N-1)

for i in range(N-1):
    if S[i] != S[i+1]:
        ans[i] = 1
total = sum(ans)
if K >= math.ceil(total/2):
    print(N-1)
else:
    print(N-1-(total-2*K))

Submission status: Accepted

Solution code:

a,b = map(int,input().split())
l = list(input())
s = 0 
for n,(x,y) in enumerate(zip(l,l[1:])):
    if x == y:s+=1
print(min(a-1,s+b*2))

Submission status: Accepted

Solution code:
t = list(map(int, input().split())); n, k = t[0], t[1];
stripe = str(input()); groups = 0
for i in range(len(stripe)-1):
    if stripe[i] != stripe[i+1]:
        groups += 1
groups += 1
if k >= groups//2:
    print(n-1)
else:
    groups = groups - 2 * k
    print(n - groups)

Submission status: Accepted

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

cnt = 1

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

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
s = input()
a = s.count("RL")
ans = 0
for i in range(n - 1):
    if s[i] == s[i + 1]:
        ans += 1
for i in range(1, k + 1):
    if n - 1 - ans > 1:
        ans += 2
    else:
        ans += n - 1 - ans
        break
print(ans)

Submission status: Accepted

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

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
l = 0
T = []
while l < N:
    ch = S[l]
    r = l+1
    while r < N:
        if S[r] == ch:
            r += 1
        else:
            break
    T.append(ch)
    l = r

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

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

def main():
    N, K = mis()
    S = input()
    ans = min(sum(S[i]==S[i+1] for i in range(N-1)) + 2*K, N-1)
    print(ans)

main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
S = input()
count_RL = 0
for i in range(N-1):
    if S[i] == 'R' and S[i+1] == 'L':
        count_RL += 1
count_edge = 0
if S[0] == 'L':
    count_edge += 1
if S[N-1] == 'R':
    count_edge += 1
count_K = 0
for i in range(K):
    if count_RL == 0:
        break
    count_RL -= 1
    count_K += 1
if (K - count_K) > 0:
    count = K - count_K
    if count_edge == 2:
        count_edge -= 1
if count_edge == 0 and count_RL == 0:
    count_edge = 1
    
not_happy = N - 2*count_RL - count_edge
print(not_happy)

Submission status: Accepted

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


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


flag = 0
S = S + 'J'
s_ = []
for i in range(0, N):
    if S[i] != S[i + 1]:
        s_.append(S[flag:i + 1])
        flag = i + 1

count = 0
for i in range(1, len(s_), 2):
    count += 1
    if s_[i][0] == 'L':
        s_[i] = s_[i].replace('L', 'R')
    elif s_[i][0] == 'R':
        s_[i] = s_[i].replace('R', 'L')

    if count == K:
        break

s_join = ''.join(s_)

happy = counthappy(s_join)
print(happy)

Submission status: Accepted

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


#count happy people
def count_happy(s):
    counter=False
    happy = 0
    for si in s:
        if si == "R" and counter:
            happy += 1
        elif si == "R":
            counter=True
        else:
            counter=False
    counter = False
    for si in s[::-1]:
        if si == "L" and counter:
            happy += 1
        elif si == "L":
            counter=True
        else:
            counter=False
    return happy

#group
happy = count_happy(s)

new_s = [s[0]]
last_char = s[0]
for si in s[1:]:
    if si == last_char:
        continue
    else:
        new_s.append(si)
        last_char = si

happy += min(len(new_s)//2, k)*2

if len(new_s)%2 == 0 and len(new_s)//2 <= k:
    happy -= 1

print(happy)

Submission status: Accepted

Solution code:
"""
幸福な人(HP)でなく不幸な人(UHP)を数える。最終的にHPは HP = N - UHP で求めることができる。
以下のような並びを考える。

    L RR LLLL R L RRR L R LLLL

同じ記号ごとにスペースで区切っている。この中で不幸な人は、両端にいる2人と、スペースで
区切られたグループに付き1人である。このようにして不幸な人の人数を数えることができた。

また、(l, r) の人々を180度回転することによって、回転するグループ両端以外の幸福な人（不幸な人）
の人数は変化しない。両端の幸不幸が変化するのみである。

境界以外を l or r に選んだとしても、幸不幸の数は変化しない。
両端でない facing, unfacing な境界をそれぞれ l, r に選ぶと、
幸福な人を2人増やすことができる。

k が十分に大きい場合、十分な数の操作を行うことによって幸福な人を最大 N - 1 人に
することができる。
"""


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

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

# k 回の操作で幸福な人を 2k 人増やすことができる
hpp += 2 * k

# N - 1 人 or k 回で N - 1 人に満たない場合は k 回で幸福にした人の数 + もともと幸福な人。
print(min(n - 1, hpp))

Submission status: Accepted

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

against = [(S[i] != S[i+1]) for i in range(N-1)]
unhappy = sum(against)

if K > unhappy:
    print(N - 1)
else:
    print(N - max(unhappy - 2 * K + 1, 1))

Submission status: Accepted

Solution code:
from copy import deepcopy
from sys import exit,setrecursionlimit
import math
from collections import defaultdict,Counter,deque
from fractions import Fraction as frac
import bisect
import sys
import logging
import heapq
logging.basicConfig(level=logging.DEBUG)

input = sys.stdin.readline

setrecursionlimit(1000000)

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

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

main()

Submission status: Accepted

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

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

l_r = 0
r_l = 0
prev_s = s[0]
ans = 0
for cur_s in s[1:]:
    if prev_s == cur_s:
        ans += 1
    elif cur_s == 'L':
        r_l += 1
    else:
        l_r += 1
    prev_s = cur_s

if min(l_r, r_l) >= k:
    ans += 2 * k
else:
    ans += 2 * min(l_r, r_l)
    if max(l_r, r_l) >= k:
        ans += k - min(l_r, r_l)
    else:
        ans += max(l_r, r_l) - min(l_r, r_l)

print(ans)

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:
N, K = map(int, input().split())
S = input()
ans = 0
l, r = 0, 0
for i in range(N-1):
	if S[i] == S[i+1]:
		ans += 1
	elif S[i] == 'L':
		l += 1
	else:
		r += 1
x = min(l, r)
if K > x:
	print(ans + 2 * x + min(K - x, abs(l - r)))
else:
	print(ans + 2 * K)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
S = input()
pre = ""
cnt = 0
for c in S:
    if c != pre:
        pre = c
        cnt += 1

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

Submission status: Accepted

Solution code:
n, k = (int(i) for i in input().split())
s = input()
ans = 0
prev = ""
for c in s:
    if c == prev:
        ans += 1
    prev = c
ans = min(ans + k*2, n-1)
print(ans)

Submission status: Accepted

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

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

if len(count) - (2*K + 1) > 0:
    print(sum(count)-len(count)+2*K)
else:
    print(sum(count)-1)

Submission status: Accepted

Solution code:
#coding: utf-8
N, K = map(int, input().split())
Smoji = input()

answer = 0
preword = ''
for s in Smoji:
  if s == preword:
    answer += 1
  preword = s

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

print(answer)

Submission status: Accepted

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

happy_count = 0
for i, c in enumerate(s):
    if c == "R":
        if i == len(s) - 1:
            pass
        elif s[i + 1] == "R":
            happy_count += 1
    else:
        if i == 0:
            pass
        elif s[i - 1] == "L":
            happy_count += 1

ret = min(happy_count + 2 * k, len(s) - 1)
print(ret)

Submission status: Accepted

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

hap = 0
bef = ''
for s in S:
  if s == bef:
    hap += 1
  bef = s

hap = hap + K*2
if hap > N-1:
  hap = N-1

print(hap)

Submission status: Accepted

Solution code:
#coding utf-8
N,K=map(int,input().split())
S=input()
LRf=-1
RLf=-1
ans=0
for i in range(N-1):
  if S[i:i+2]=="LL" or S[i:i+2]=="RR":
    ans+=1

for i in range(N-1):
  if K==0:
    break
  if S[i:i+2]=="LR" and RLf==-1:
    LRf=i
  elif S[i:i+2]=="RL" and LRf>=0:
    LRf=-1
    ans+=2
    K-=1
  elif S[i:i+2]=="RL" and LRf==-1:
    RLf=i
  elif S[i:i+2]=="LR" and RLf>=0:
    RLf=-1
    ans+=2
    K-=1
  if i==N-2:
    if RLf>=0 or LRf>=0:
      ans +=1
      K-=1

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
 
import numpy as np
 
N, K = map(int, input().split())
S = np.array(list(input()), dtype='U1')
 
S_slide = S[1:]
S_2 = S[:-1]
 
happiness = np.count_nonzero(S_slide == S_2)
happiness += 2*K
 
happiness = min(happiness, N-1)
 
print(happiness)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(5 * 10**5)
input=sys.stdin.readline

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

chunks = 0
between = 0

prev = S[0]

for s in S:
    if s != prev:
        if s == S[0]:
            between += 1
        chunks +=1
    prev = s


if K <= between:
    ans = N - chunks + 2 * K
else:
    ans = N - 1

print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import re
n, k = [int(i) for i in input().split()]
s = input()
cnt = sum([1 for i in range(n-1) if s[i+1] == s[i]])
flg = (s[-1] == "R") + (s[0] == "R")
s += "L"
red_ls = re.findall(r"RL", s)
if len(red_ls) > k:
    print(cnt + k * 2)
else:
    if flg > 0:
        print(cnt + (len(red_ls) - flg) * 2 + flg)
    else:
        print(cnt + len(red_ls) * 2)

Submission status: Accepted

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

tmp = S[0]
cnt = 0
for i in range(1, N):
    if tmp == S[i]:
        cnt += 1
    else:
        tmp = S[i]

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

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import math

def input():
    return sys.stdin.readline().strip()

def iinput():
    return int(input())

def finput():
    return float(input())

def tinput():
    return input().split()

def rinput():
    return map(int, tinput())

def rlinput():
    return list(rinput())

def pro(k, l, n):
    if l < n:
        if k == 0:
            return(n - l)
        return (n - l + 2)
    if l == n:
        if k == 0:
            return 0
        elif k == 1:
            return 1
        return 3
    else:
        l -= n - 1
        if l == k:
            return 1
        elif l > k:
            return 0
        if l < k - 1:
            return 2
        else:
            return 3
            

def rt(k, l , n):
    if k < n:
        if l == 0:
            return (k * 2 + n)
        return (n + k * 2 - 1)
    elif k == n:
        if l == 1:
            return (k * 3 - 2)
        elif l == 0:
            return (k * 3)
        return (k * 3 - 3)
    else:
        k -= n - 1
        if k == l:
            return (n * 3 - 2)
        elif k > l:
            return (n * 3)
        if k < l - 1:
            return ((n - 1) * 3 - 1)
        else:
            return ((n - 1) * 3)



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


main()

Submission status: Accepted

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

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

Submission status: Accepted

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

# もっとも左の文字に合わせるだけ。
now = S[0]
cnt = 0
encode = []

for i in range(1, N):
    if now != S[i]:
        cnt += 1
    now = S[i]

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