You like playing chess tournaments online.

In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").

The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.

After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.

Compute the maximum score you can get by cheating in the optimal way.


-----Input-----

Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) — the number of test cases. The description of the test cases follows.

The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) – the number of games played and the number of outcomes that you can change.

The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.

It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.


-----Output-----

For each testcase, print a single integer – the maximum score you can get by cheating in the optimal way.


-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW

Output
7
11
6
26
46
0
1
6



-----Note-----

Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).

An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.

Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).

An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.

Difficulty: MEDIUM

Solutions:
import sys
import bisect as bi
import collections as cc
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n, k) = I()
	s = list(input())
	if s.count('W') == 0:
		now = min(k, n)
		print(max(0, 1 + 2 * (now - 1)))
		continue
	i = 0
	gap = []
	for i in range(n):
		if s[i] == 'W':
			gap.append(i)
	ne = []
	for i in range(len(gap) - 1):
		ne.append([gap[i], gap[i + 1], gap[i + 1] - gap[i] - 1])
	ne.sort(key=lambda x: x[2])
	for i in ne:
		now = i[0] + 1
		while now < i[1] and k:
			s[now] = 'W'
			now += 1
			k -= 1
		if not k:
			break
	temp = []
	if s[0] != 'W':
		temp.append([-1, gap[0], gap[0] - -1 - 1])
	if s[-1] != 'W':
		temp.append([gap[-1], n, n - gap[-1] - 1])
	temp.sort(key=lambda x: x[2])
	for i in temp:
		if i[0] == -1:
			now = i[1] - 1
			while now >= 0 and k:
				k -= 1
				s[now] = 'W'
				now -= 1
		else:
			now = i[0] + 1
			while now < i[1] and k:
				s[now] = 'W'
				k -= 1
				now += 1
		if not k:
			break
	f = 0
	cnt = 0
	ans = 0
	for i in range(n):
		if not f and s[i] == 'W':
			f = 1
			ans += 1
		elif f and s[i] == 'W':
			ans += 2
		else:
			f = 0
	print(ans)


import sys
for _ in range(int(sys.stdin.readline())):
	(N, k) = map(int, sys.stdin.readline().split())
	arr = list(map(str, input().strip()))
	dic = []
	temp = k
	lose = 0
	streak = 0
	if 'W' not in arr:
		print(max(0, 2 * k - 1))
	elif 'L' not in arr:
		print(2 * N - 1)
	else:
		for i in range(N):
			if arr[i] == 'L':
				lose += 1
				if arr[i - 1] == 'W' or i == 0:
					dic.append(1)
				else:
					dic[len(dic) - 1] += 1
			else:
				if i > 0:
					if arr[i - 1] == 'W':
						continue
				streak += 1
		(first, last) = (0, 0)
		if arr[0] == 'L':
			first = dic[0]
		if arr[N - 1] == 'L':
			last = dic[len(dic) - 1]
		dic.sort()
		for item in dic:
			if k - item >= 0:
				if item == first:
					first = 0
					continue
				elif item == last:
					last = 0
					continue
				k -= item
				streak -= 1
			else:
				break
		wins = min(N, N - lose + temp)
		print(max(2 * wins - streak, 0))


for _ in ' ' * int(input()):
	(n, k) = map(int, input().split())
	s = list(input())
	if 'W' not in s:
		print(max(min(k, n) * 2 - 1, 0))
	elif k >= s.count('L'):
		print(n * 2 - 1)
	else:
		cnt = []
		sm = 0
		for i in range(n):
			if s[i] == 'W':
				sm += 1
		ind = s.index('W')
		for i in range(ind + 1, n):
			if s[i] == 'W':
				cnt.append(i - ind - 1)
				ind = i
		cnt.sort()
		for i in cnt:
			if k >= i:
				sm += 2 * i + 1
				k -= i
		if k > 0:
			sm += 2 * k
		print(sm)


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
sys.setrecursionlimit(99999)
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input().strip('L')
	cw = s.count('W') + k
	t = []
	for (key, value) in itertools.groupby(s):
		if key == 'L':
			t.append(len(list(value)))
	t.sort()
	while t and t[0] <= k:
		k -= t.pop(0)
	print(max(0, 2 * min(n, cw) - len(t) - 1))


I = input
for _ in [0] * int(I()):
	(n, k) = map(int, I().split())
	a = sorted(map(len, I().strip('L').split('W')))
	m = len(a) + k
	while a and a[0] <= k:
		k -= a.pop(0)
	print((2 * min(n, m - 1) - len(a) or 1) - 1)


nums = int(input().strip())
for _ in range(nums):
	(n, k) = map(int, input().strip().split())
	s = input().strip()
	(lw, rw) = (s.find('W'), s.rfind('W'))
	res = cur_num = 0
	if lw == rw:
		if lw == -1:
			res = 2 * k - 1
		else:
			res = 2 * k + 1
		res = min(2 * len(s) - 1, res)
	else:
		part = []
		for i in range(lw, rw + 1):
			if s[i] == 'W':
				if i > lw and s[i - 1] == 'L':
					part.append(cur_num)
					cur_num = 0
				if i > lw and s[i - 1] == 'W':
					res += 2
				else:
					res += 1
			else:
				cur_num += 1
		if k >= sum(part) + lw + len(s) - rw - 1:
			res = 2 * len(s) - 1
		else:
			part.sort()
			for i in range(len(part)):
				if k >= part[i]:
					res += 2 * part[i] + 1
					k -= part[i]
				else:
					break
			res += 2 * k
	print(max(res, 0))


for _ in range(int(input())):
	(N, K) = map(int, input().split())
	S = [x for x in input()]
	l = []
	cnt = 0
	check = -1
	for i in range(N):
		if S[i] == 'L':
			cnt += 1
			if check == -1:
				check = i
		elif cnt >= 1:
			if check != 0:
				l.append([cnt, check])
			cnt = 0
			check = -1
	l.sort()
	for (a, s) in l:
		for x in range(s, s + a):
			if K == 0:
				break
			S[x] = 'W'
			K -= 1
	if K >= 1:
		if 'W' not in S:
			for i in range(K):
				S[i] = 'W'
		else:
			for i in range(S.index('W') - 1, -1, -1):
				S[i] = 'W'
				K -= 1
				if K == 0:
					break
			if K >= 1:
				for p in range(N - 1, -1, -1):
					if S[p] == 'W':
						for i in range(p + 1, N):
							S[i] = 'W'
							K -= 1
							if K == 0:
								break
						break
	ans = 0
	for i in range(N):
		if S[i] == 'W':
			if i == 0 or S[i - 1] == 'L':
				ans += 1
			else:
				ans += 2
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	state = input()
	state = [i for i in state]
	(ans, prev) = (0, 0)
	store = []
	if state[0] == 'W':
		rang = [-1]
	else:
		rang = []
	for i in range(len(state)):
		if state[i] == 'W':
			if len(rang) == 1:
				if rang[0] == i - 1:
					rang = [i]
				else:
					store.append((i - rang[0] - 1, rang[0] + 1, i))
					rang = [i]
			else:
				rang = [i]
	last = rang[0] if rang else 0
	store.sort()
	if k > 0:
		for i in store:
			for j in range(i[1], i[2]):
				state[j] = 'W'
				k -= 1
				if k == 0:
					break
			if k == 0:
				break
	if k > 0:
		for i in range(last + 1, len(state)):
			if state[i] == 'L':
				state[i] = 'W'
				k -= 1
			if k == 0:
				break
	if k > 0:
		for i in range(len(state) - 1, -1, -1):
			if state[i] == 'L':
				state[i] = 'W'
				k -= 1
			if k == 0:
				break
	if state[0] == 'W':
		ans = 1
	else:
		ans = 0
	for i in range(1, len(state)):
		if state[i] == 'W':
			if state[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	sys.stdout.write(str(ans) + '\n')


for _ in range(int(input())):
	(a, b) = map(int, input().split())
	s = input()
	if s == 'L' * a:
		if b:
			print(b * 2 - 1)
		else:
			print(0)
	elif s == 'W' * a:
		print(a * 2 - 1)
	else:
		ans = 0
		(fst, lst) = (-1, -1)
		if s[0] == 'W':
			ans += 1
			fst = 0
			lst = 0
		for i in range(1, a):
			if s[i] == 'W':
				if fst == -1:
					fst = i
				if s[i - 1] == 'W':
					ans += 1
				ans += 1
				lst = i
		if b == 0:
			print(ans)
			continue
		k = s[fst:lst + 1].split('W')
		k.sort()
		for i in k:
			if len(i):
				if b >= len(i):
					ans += len(i) * 2 + 1
					b -= len(i)
				else:
					ans += b * 2
					b = 0
			if b == 0:
				break
		ans += min(b, fst + a - lst - 1) * 2
		print(ans)


import sys
input = sys.stdin.readline

def get_close(n, i, res):
	while i < n and res[i] == 'L':
		i += 1
	return i - 1

def calc(n, res):
	count = 0
	for i in range(n):
		if i > 0 and res[i - 1] == res[i] == 'W':
			count += 2
		elif res[i] == 'W':
			count += 1
	return count

def solve(n, k, res):
	gaps = []
	rem = []
	i = 0
	while i < n:
		if res[i] == 'L':
			(op, cl) = (i, get_close(n, i + 1, res))
			gaps.append((cl - op + 1, op, cl))
			i = cl + 1
			if op == 0 or cl == n - 1:
				rem.append(gaps.pop())
		else:
			i += 1
	gaps.sort()
	for (gap, start, stop) in gaps:
		if not k:
			break
		for i in range(start, stop + 1):
			if k:
				res[i] = 'W'
				k -= 1
			else:
				break
	for (_, start, stop) in rem:
		if start == 0:
			g = reversed(range(start, stop + 1))
		else:
			g = range(start, stop + 1)
		for i in g:
			if k:
				res[i] = 'W'
				k -= 1
			else:
				break
	return calc(n, res)
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	res = list(input().rstrip())
	print(solve(n, k, res))


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		kCpy = k
		s = input()
		WCnt = 0
		LCnt = 0
		LSegment = []
		cnt = 0
		for elem in s:
			if elem == 'W':
				LSegment.append(cnt)
				cnt = 0
				WCnt += 1
			else:
				cnt += 1
				LCnt += 1
		if not LSegment:
			print(max(2 * k - 1, 0))
		else:
			WBreaker = sorted(LSegment[1:])
			if LCnt <= k:
				print(2 * n - 1)
			else:
				broken = 0
				for elem in WBreaker:
					if k >= elem:
						k -= elem
						broken += 1
					else:
						break
				print(max(2 * (WCnt + kCpy) - len(WBreaker) + broken - 1, 0))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
for _ in range(t):
	gaps = []
	winseq = 0
	(n, k) = map(int, input().split())
	wins = k
	s = input()
	l = 1
	flag1 = 0
	for i in range(n):
		if s[i] == 'W':
			wins += 1
			if i < len(s) - 1:
				if s[i + 1] == 'L':
					winseq += 1
			else:
				winseq += 1
		else:
			if i == n - 1:
				continue
			if i == 0:
				if s[1] == 'L':
					flag1 = 1
				else:
					continue
			elif s[i + 1] == 'L':
				l += 1
			elif flag1 == 0:
				gaps.append(l)
				l = 1
			else:
				flag1 = 0
				l = 1
	if wins >= n:
		print(2 * n - 1)
	else:
		if winseq == 0 and k != 0:
			winseq = 1
		gaps.sort()
		for length in gaps:
			if length <= k:
				k -= length
				winseq -= 1
			else:
				break
		print(2 * wins - winseq)


def main():
	t = int(input())
	for _ in range(t):
		(n, k) = (int(x) for x in input().split())
		s = input()
		print(solver(s, n, k))

def solver(s, n, k):
	cur_score = getCurScore(s)
	lcount = s.count('L')
	if lcount <= k:
		return 2 * n - 1
	elif lcount == n:
		return max(2 * k - 1, 0)
	llist = []
	i = s.find('W')
	cur = 0
	for c in s[i:]:
		if c == 'L':
			cur += 1
		elif cur != 0:
			llist.append(cur)
			cur = 0
	llist.sort()
	point_increase = 0
	for x in llist:
		if x <= k:
			point_increase += 2 * x + 1
			k -= x
		else:
			point_increase += 2 * k
			return cur_score + point_increase
	point_increase += 2 * k
	return cur_score + point_increase

def getCurScore(s):
	score = 0
	if s[0] == 'W':
		score += 1
	for i in range(1, len(s)):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				score += 2
			else:
				score += 1
	return score
main()


from bisect import *
from math import *
from collections import Counter, defaultdict
I = lambda : int(input())
M = lambda : map(int, input().split())
LI = lambda : list(map(int, input().split()))

def split(s, c):
	b = []
	ch = ''
	for i in range(len(s)):
		if s[i] == c:
			ch += c
		else:
			if ch != '':
				b += [ch]
			ch = ''
	if ch != '':
		b += [ch]
	return b

def solve():
	(n, k) = M()
	s = input()
	ans = 0
	a = split(s, 'W')
	for i in range(len(a)):
		if a[i] != '':
			ans += (len(a[i]) - 1) * 2
			ans += 1
	ind1 = -1
	ind2 = -1
	for i in range(n):
		if s[i] == 'W':
			ind1 = i
			break
	for i in range(n - 1, -1, -1):
		if s[i] == 'W':
			ind2 = i
			break
	a = split(s[ind1:ind2], 'L')
	b = sorted(a)
	for i in range(len(b)):
		c = len(b[i])
		if c <= k:
			ans += c * 2 + 1
		else:
			ans += k * 2
		k -= min(k, c)
		if k == 0:
			break
	c = ind1
	if ind1 != -1:
		c += n - ind2
		c -= 1
		ans += min(c, k) * 2
	elif k != 0:
		ans += (min(len(s), k) - 1) * 2
		ans += 1
		ans = max(0, ans)
	print(min(ans, len(s) * 2 - 1))
for _ in range(I()):
	solve()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = sorted(map(len, input().strip('L').split('W')))
	m = len(l) - 1 + k
	while l and l[0] <= k:
		k -= l.pop(0)
	if m >= n:
		print(2 * n - 1)
	else:
		print((2 * m - len(l) or 1) - 1)


import sys

def solve(outcomes, k, raw):
	n = len(outcomes)
	nw = sum(outcomes)
	nl = n - nw
	last = 0
	score = 0
	for s in outcomes:
		score += 0 if s == 0 else 1 if last == 0 else 2
		last = s
	if k == 0:
		return score
	elif k >= nl:
		return 2 * n - 1
	elif nw == 0:
		return 2 * k - 1
	else:
		lgroups = [len(g) for g in raw.split('W') if len(g) > 0]
		if outcomes[0] == 0:
			lgroups.pop(0)
		if nw > 0:
			if outcomes[-1] == 0:
				lgroups.pop()
		lgroups.sort()
		for grp in lgroups:
			if k >= grp:
				score += 2 * grp + 1
				k -= grp
			else:
				score += 2 * k
				k = 0
				break
		if k > 0:
			score += 2 * k
			k = 0
		return score
IN = [x.strip() for x in sys.stdin.readlines()]
T = int(IN[0])
cur = 1
for ti in range(T):
	(n, k) = [int(x) for x in IN[cur].split(' ')]
	outcomes = [1 if c == 'W' else 0 for c in IN[cur + 1]]
	res = solve(outcomes, k, IN[cur + 1])
	print(res)
	cur += 2


class Streak:

	def __init__(self, start_ind, end_ind):
		self.start_ind = start_ind
		self.end_ind = end_ind

class StreakNbors:

	def __init__(self, streak_a, streak_b):
		self.streak_a = streak_a
		self.streak_b = streak_b

	def get_gap(self):
		return self.streak_b.start_ind - self.streak_a.end_ind - 1

	def close_gap(self):
		self.streak_a.end_ind += 1
t = int(input())
for it in range(0, t):
	(n, k) = tuple(list(map(int, input().split(' '))))
	results = [char for char in input()]
	if n == 1:
		if k >= 1:
			results[0] = 'W'
	else:
		streak_list = []
		current_streak = None
		for i in range(0, len(results)):
			if results[i] == 'W':
				if i == 0 or results[i - 1] == 'L':
					current_streak = Streak(i, i)
					streak_list.append(current_streak)
				else:
					current_streak.end_ind = i
		if streak_list:
			streak_nbors_list = []
			for i in range(0, len(streak_list) - 1):
				streak_nbors_list.append(StreakNbors(streak_list[i], streak_list[i + 1]))
			streak_nbors_list = sorted(streak_nbors_list, key=lambda streak_nbors: streak_nbors.get_gap())
			streak_nbors_ind = 0
			changes = 0
			while changes < k and streak_nbors_ind < len(streak_nbors_list):
				current_streak_nbors = streak_nbors_list[streak_nbors_ind]
				if current_streak_nbors.get_gap() > 0:
					current_streak_nbors.close_gap()
					changes += 1
				else:
					streak_nbors_ind += 1
			for i in range(0, len(streak_nbors_list)):
				current_streak_nbors = streak_nbors_list[i]
				streak_a_start_ind = current_streak_nbors.streak_a.start_ind
				streak_a_end_ind = current_streak_nbors.streak_a.end_ind
				for j in range(streak_a_start_ind, streak_a_end_ind + 1):
					results[j] = 'W'
				streak_b_start_ind = current_streak_nbors.streak_b.start_ind
				streak_b_end_ind = current_streak_nbors.streak_b.end_ind
				for j in range(streak_b_start_ind, streak_b_end_ind + 1):
					results[j] = 'W'
			min_streak_ind = 200001
			max_streak_ind = -1
			for i in range(0, len(results)):
				if results[i] == 'W':
					min_streak_ind = min(i, min_streak_ind)
					max_streak_ind = max(i, min_streak_ind)
			while changes < k:
				if min_streak_ind > 0:
					min_streak_ind -= 1
					results[min_streak_ind] = 'W'
					changes += 1
				elif max_streak_ind < len(results) - 1:
					max_streak_ind += 1
					results[max_streak_ind] = 'W'
					changes += 1
				else:
					break
		else:
			for i in range(0, k):
				results[i] = 'W'
	score = 0
	for i in range(0, n):
		if results[i] == 'W':
			score += 1
			if i > 0 and results[i - 1] == 'W':
				score += 1
	print(score)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	score = 0
	tmp = s.count('L')
	for i in range(1, n):
		if s[i] == 'W' and s[i - 1] == 'W':
			score += 2
		elif s[i] == 'W':
			score += 1
	if s[0] == 'W':
		score += 1
	if k == 0:
		print(score)
		continue
	res = []
	idx = s.find('W')
	count = 0
	for i in range(idx + 1, n):
		if s[i] == 'L':
			count += 1
		else:
			res.append(count)
			count = 0
	res = list(filter(lambda x: x != 0, res))
	res.sort()
	i = 0
	while k > 0 and i < len(res):
		if res[i] <= k:
			k -= res[i]
			score += 2 * res[i]
			score += 1
		else:
			score += 2 * k
			k = 0
		i += 1
	if 'W' in s:
		score += 2 * min(k, tmp - sum(res))
	elif k <= n:
		score += 2 * k - 1
	else:
		score += 2 * n - 1
	print(score)


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd, log
from collections import Counter
from pprint import pprint

def main():
	(n, m) = map(int, input().split())
	s = [c for c in input()]
	start = 0
	end = 0
	a = []
	wc = s.count('W')
	while end < n and start < n:
		if s[start] == 'L':
			end = start
			while end < n and s[end] == 'L':
				end += 1
			if start != 0 and end != n:
				a.append((end - start, start))
			start = end - 1
		start += 1
	a.sort(reverse=True)
	while m and len(a):
		(l, st) = a.pop()
		for i in range(st, st + l):
			m -= 1
			s[i] = 'W'
			if not m:
				break
	ind = 0
	while ind < n and s[ind] == 'L':
		ind += 1
	j = ind - 1
	while j >= 0 and m:
		s[j] = 'W'
		j -= 1
		m -= 1
	end = n - 1
	while end >= 0 and s[end] == 'L':
		end -= 1
	j = end + 1
	while j < n and m:
		s[j] = 'W'
		j += 1
		m -= 1
	ans = 0
	if s[0] == 'W':
		ans += 1
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				ans += 1
			ans += 1
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	main()


import sys
input = iter(sys.stdin.read().splitlines()).__next__
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	num_losses = s.count('L')
	if k >= num_losses:
		print(2 * n - 1)
		continue
	score = 1 if s[0] == 'W' else 0
	interval_lengths = [] if s[0] == 'W' else [0]
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				score += 2
			else:
				score += 1
				interval_lengths[-1] += i
		elif s[i - 1] == 'W':
			interval_lengths.append(-i)
	if s[-1] == 'L':
		last_length = interval_lengths.pop()
		last_length += n
	else:
		last_length = 0
	if s[0] == 'L' and interval_lengths:
		first_length = interval_lengths.remove(interval_lengths[0])
	if sum(interval_lengths) <= k:
		num_wins = s.count('W') + k
		print(max(2 * num_wins - 1, 0))
		continue
	interval_lengths.sort(reverse=True)
	while k:
		next_interval = interval_lengths.pop()
		if k >= next_interval:
			k -= next_interval
			score += 2 * next_interval + 1
		else:
			score += 2 * k
			k = 0
	print(score)


import sys, os, io
I = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for tc in range(1, 1 + int(I())):
	(n, k) = map(int, I().split())
	s = I().rstrip().decode('utf-8')
	if s.find('W') == -1:
		ans = max(0, 2 * k - 1)
		print(ans)
		continue
	b = 0
	l = []
	i = 0
	while i < n:
		if s[i] == 'W':
			break
		else:
			b += 1
		i += 1
	a = 0
	while i < n:
		if s[i] == 'W':
			if a > 0:
				l.append(a)
			a = 0
		else:
			a += 1
		i += 1
	e = a
	l.sort()
	ans = 0
	for i in range(n):
		if s[i] == 'W':
			ans += 1
			if i > 0:
				if s[i - 1] == 'W':
					ans += 1
	for c in l:
		if c <= k:
			k -= c
			ans += 2 * c + 1
		elif k > 0:
			ans += 2 * k
			k = 0
	ans += 2 * min(k, b + e)
	print(ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import defaultdict

def gift():
	for _ in range(t):
		(n, k) = list(map(int, input().split()))
		array = input()
		dic = defaultdict(lambda : 0)
		dicLis = []
		curr = 0
		win = 0
		score = 0
		for i in range(n):
			if array[i] == 'W':
				if win > 0:
					score += 2
				else:
					score += 1
				win += 1
				dicLis.append(curr)
				curr = 0
			else:
				win = 0
				curr += 1
		dicLis.append(curr)
		for i in range(1, len(dicLis) - 1):
			if dicLis[i]:
				dic[dicLis[i]] += 1
		itemRino = sorted(list(dic.items()))
		for ele in itemRino:
			(gap, count) = ele
			while count:
				if k >= gap:
					score += gap * 2 + 1
				else:
					score += k * 2
				count -= 1
				k -= gap
				if k <= 0:
					break
			if k <= 0:
				break
		if k > 0:
			if len(dicLis) > 1 and dicLis[-1] > 0:
				score += 2 * min(k, dicLis[-1])
				k -= dicLis[-1]
		if k > 0:
			if len(dicLis) > 1:
				score += 2 * min(k, dicLis[0])
				k -= dicLis[0]
			else:
				score += 2 * min(k, dicLis[0]) - 1
		yield score
t = int(input())
ans = gift()
print(*ans, sep='\n')


I = input
for _ in [0] * int(I()):
	(n, k) = map(int, I().split())
	s = I()
	a = sorted(map(len, filter(None, s.strip('L').split('W'))))
	r = 0
	while a and r + a[0] <= k:
		r += a.pop(0)
	print((2 * min(n, s.count('W') + k) - len(a) or 1) - 1)


import os
import sys
from io import BytesIO, IOBase
import math
from itertools import permutations
from decimal import *
getcontext().prec = 25
MOD = pow(10, 9) + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	(n, k) = map(int, input().split(' '))
	l = input()
	if n == k:
		print(2 * k - 1)
	else:
		t = 0
		z = []
		w = L = False
		le = pre = 0
		for i in range(n):
			if l[i] == 'L':
				L = True
				pre += 1
			else:
				break
		start = max(1, pre)
		if l[0] == 'W':
			t += 1
		for i in range(start, n):
			if l[i] == 'W':
				w = True
				if le:
					z.append(le)
					le = 0
				if l[i - 1] == 'W':
					t += 2
				else:
					t += 1
			if l[i] == 'L':
				L = True
				le += 1
		extra = le
		z.sort()
		if k == 0 or not L:
			print(t)
		elif not extra and (not z):
			if not w:
				print(2 * min(pre, k) - 1)
			else:
				print(2 * min(pre, k) + t)
		elif not z:
			t += 2 * min(pre, k)
			k = max(0, k - pre)
			t += 2 * min(k, extra)
			print(t)
		elif z:
			for i in range(len(z)):
				if z[i] <= k:
					k -= z[i]
					t += 2 * z[i] + 1
				else:
					t += 2 * k
					k = 0
					break
			if k:
				t += 2 * min(pre, k)
				k = max(0, k - pre)
				t += 2 * min(k, extra)
			print(t)


import math
t = int(input())
for q in range(t):
	(n, k) = [int(i) for i in input().split()]
	s = input()
	C = []
	b = False
	p = 0
	rest = 0
	for i in s:
		if i == 'W' and (not b):
			b = True
		elif i == 'L' and b:
			p += 1
		elif i == 'W' and b and p:
			if p:
				C.append(p)
			p = 0
		elif i == 'L' and (not b):
			rest += 1
	C.sort()
	prof = 0
	rest += p
	for i in C:
		if k >= i:
			prof += 2 * i + 1
			k -= i
		else:
			prof += k * 2
			k = 0
			break
	if k:
		if k >= rest:
			prof += rest * 2
			k -= rest
		else:
			prof += k * 2
			k = 0
	if rest == len(s) and prof:
		prof -= 1
	res = 0
	b = False
	for i in s:
		if i == 'W' and b:
			res += 2
		elif i == 'W' and (not b):
			res += 1
			b = True
		else:
			b = False
	print(prof + res)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	s = list(input())
	o = -1

	def score(s):
		if s[0] == 'W':
			ans = 1
			x = 1
		else:
			ans = 0
			x = 0
		for i in range(1, len(s)):
			if s[i] == 'W' and x == 1:
				ans += 2
			elif s[i] == 'W' and x == 0:
				x = 1
				ans += 1
			else:
				x = 0
		return ans
	for i in range(n):
		if s[i] == 'W':
			o = i
			break
	o1 = -2
	for i in range(n - 1, -1, -1):
		if s[i] == 'W':
			o1 = i
			break
	if k == 0:
		print(score(s))
	elif o == -1 or o1 == o:
		print(2 * min(k + (o1 == o), n) - 1)
	else:
		r = []
		st = o + 1
		for j in range(o + 1, o1 + 1):
			if s[j] == 'W':
				r.append([st, j])
				st = j + 1
		r = sorted(r, key=lambda x: x[1] - x[0])
		for j in r:
			for d in range(j[0], j[1]):
				if k > 0:
					k -= 1
					s[d] = 'W'
				else:
					break
		for d in range(o - 1, -1, -1):
			if k > 0:
				k -= 1
				s[d] = 'W'
			else:
				break
		for d in range(o1 + 1, len(s)):
			if k > 0:
				k -= 1
				s[d] = 'W'
			else:
				break
		print(score(s))


t = int(input())
for i in range(t):
	(n, k) = map(int, input().strip(' ').split(' '))
	s = input().strip(' ')
	ind = s.find('W')
	if ind == -1:
		if k == 0:
			print(0)
		else:
			print(2 * k - 1)
		continue
	pre = 1
	c = 0
	lcount = []
	wins = 1
	winningstreak = 0
	for i in range(ind + 1, n):
		if s[i] == 'W':
			if pre == 0:
				lcount.append(c)
				c = 0
			wins += 1
			pre = 1
		else:
			if pre == 1:
				winningstreak += 1
			c += 1
			pre = 0
	if pre:
		winningstreak += 1
	wins += k
	if wins >= n:
		print(2 * n - 1)
		continue
	lcount.sort()
	x = 0
	for i in lcount:
		if k >= i:
			x += 1
			k -= i
		else:
			break
	ans = 2 * wins - winningstreak + x
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(input())
	(st, ed) = (0, 0)
	for i in range(n):
		if s[i] == 'W':
			stw = i
			break
		st += 1
	if st != n:
		for j in range(n - 1, -1, -1):
			if s[j] == 'W':
				edw = j
				break
			ed += 1
	else:
		print(max(0, k * 2 - 1))
		continue
	l = []
	i = s.index('W')
	while i < n:
		if s[i] == 'W':
			i += 1
		else:
			j = i
			c = 0
			while j < n and s[j] == 'L':
				c += 1
				j += 1
			if j == n:
				break
			l.append([c, i])
			i = j
	l.sort()
	for e in l:
		if e[0] <= k:
			k -= e[0]
			idx = e[1]
			for p in range(idx, idx + e[0]):
				s[p] = 'W'
		else:
			idx = e[1]
			for p in range(idx, idx + k):
				s[p] = 'W'
				k = 0
	if k != 0:
		if st != 0:
			for i in range(stw - 1, -1, -1):
				s[i] = 'W'
				k -= 1
				if k == 0:
					break
	if k != 0:
		if ed != 0:
			for i in range(edw + 1, n):
				s[i] = 'W'
				k -= 1
				if k == 0:
					break
	ans = 0
	pre = 0
	for i in range(n):
		if s[i] == 'L':
			pre = 0
			continue
		elif pre == 0:
			ans += 1
			pre = 1
		else:
			ans += 2
	print(ans)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	for _ in range(ii()):
		(n, k) = mi()
		s = si()
		ans = 0
		p = 0
		l = []
		for i in range(n):
			if s[i] == 'W':
				if p == 0:
					ans += 1
				else:
					ans += 2
				p = 1
			else:
				p = 0
		cnt = 0
		first = -1
		last = -1
		for i in range(n):
			if s[i] == 'L':
				cnt += 1
			else:
				if cnt != 0:
					if s[0] == 'L' and first == -1:
						first = cnt
					else:
						l.append(cnt)
				cnt = 0
		if cnt != 0:
			last = cnt
		l.sort()
		if last == n:
			print(max(2 * k - 1, 0))
			continue
		for i in range(len(l)):
			if l[i] <= k:
				ans += l[i] * 2 + 1
				k -= l[i]
			else:
				ans += k * 2
				k = 0
				break
		if k != 0:
			if last != -1:
				p = min(last, k)
				ans += p * 2
				k -= p
		if k != 0:
			if first != -1:
				p = min(first, k)
				if p >= first:
					ans += p * 2
				else:
					ans += p * 2
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def recal(l, n, k):
	result = 0
	cur = []
	last_lose = 0
	dex = 0
	have_win = False
	for i in l:
		if i == 'W':
			if last_lose == 0:
				if have_win:
					result += 2
				else:
					result += 1
					have_win = True
			else:
				result += 1
				cur += [last_lose]
				last_lose = 0
		elif have_win:
			last_lose += 1
		else:
			dex += 1
	if last_lose:
		dex += last_lose
	cur.sort(reverse=True)
	while cur and k >= cur[-1]:
		result += cur[-1] * 2 + 1
		k -= cur[-1]
		cur.pop()
	if cur:
		dex += sum(cur)
	if k != 0:
		if have_win:
			result += min(dex, k) * 2
		else:
			result += min(dex, k) * 2 - 1
	print(result)
t = int(input())
while t > 0:
	(n, k) = map(int, input().split())
	l = input()
	recal(l, n, k)
	t -= 1


t = int(input())

def answer(n, k, s):
	win = []
	for i in range(n):
		if s[i] == 'W':
			win.append(i)
	l = len(win)
	if l <= 1:
		print(min(max(2 * (k + l) - 1, 0), 2 * n - 1))
	elif win[-1] - l + 1 <= k:
		ans = min(2 * (k + l) - 1, 2 * n - 1)
		print(ans)
	else:
		ans = 1
		for i in range(l - 1):
			if win[i + 1] - win[i] == 1:
				ans += 2
			else:
				ans += 1
		delta = [win[i + 1] - win[i] - 1 for i in range(l - 1)]
		delta.sort()
		flag = k
		j = 0
		while flag > 0 and j < l - 1:
			d = delta[j]
			if d != 0:
				if flag >= d:
					flag -= d
					ans += 2 * d + 1
				else:
					ans += 2 * flag
					flag = -1
			j += 1
		if flag > 0:
			ans += 2 * flag
		print(ans)
for i in range(t):
	(n, k) = map(int, input().split())
	s = list(str(input()))
	answer(n, k, s)


(z, zz) = (input, lambda : list(map(int, z().split())))
fast = lambda : stdin.readline().strip()
zzz = lambda : [int(i) for i in stdin.readline().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
ans = []
for _ in range(num):
	(n, k) = zz()
	arr = sorted(map(len, fast().strip('L').split('W')))
	m = len(arr) + k
	while arr and arr[0] <= k:
		k -= arr.pop(0)
	ans.append((2 * min(n, m - 1) - len(arr) or 1) - 1)
for _ in ans:
	print(_)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	s = s.replace('WL', 'W L').replace('LW', 'L W')
	s = s.split()
	ls = [len(li) for li in s if li[0] == 'L']
	wstr = 0
	for si in s:
		wstr += si[0] == 'W'
	wins = n - sum(ls)
	if wins + k >= n:
		print(n * 2 - 1)
		continue
	if not wins:
		if k == 0:
			print(k)
		else:
			print(2 * k - 1)
		continue
	wins += k
	if s[0][0] == 'L':
		ls[0] = 10000000000.0
	if s[-1][0] == 'L':
		ls[-1] = 10000000000.0
	ls.sort()
	for li in ls:
		if li > k:
			break
		wstr -= 1
		k -= li
	print(wins * 2 - wstr)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	s = input()
	k = min(k, s.count('L'))
	arr = []
	cur = 0
	sc = 0
	se = False
	if s[0] == 'W':
		sc += 1
	for e in s:
		if e == 'L':
			cur += 1
		else:
			if cur > 0 and se:
				arr.append(cur)
			se = True
			cur = 0
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				sc += 2
			else:
				sc += 1
	arr.sort()
	arr.reverse()
	while len(arr) > 0 and arr[-1] <= k:
		k -= arr[-1]
		sc += arr[-1] * 2 + 1
		arr.pop()
	sc += k * 2
	if k > 0 and s.count('W') == 0:
		sc -= 1
	print(sc)


t = int(input())

def cheatScore(s, n, k):
	lose = 0
	score = 0
	start = 0
	tmp = []
	flag = 0
	Alllose = 1
	for c in s:
		if c != 'W':
			continue
		else:
			Alllose = 0
			break
	if Alllose:
		return max(0, 2 * min(n, k) - 1)
	for i in range(len(s)):
		if i == 0:
			if s[i] == 'L':
				count = 1
				flag = 1
			else:
				continue
		if s[i] == 'L':
			if s[i - 1] == 'W':
				count = 1
			elif s[i - 1] == 'L':
				count += 1
		elif s[i - 1] == 'L':
			tmp.append(count)
		else:
			continue
	stEnd = 0
	if flag:
		stEnd += tmp.pop(0)
	if s[-1] == 'L':
		stEnd += count
	tmp = sorted(tmp)
	for i in range(len(s)):
		if i == 0:
			if s[i] == 'W':
				score += 1
			else:
				lose += 1
			continue
		if s[i] == 'W':
			if s[i - 1] == 'W':
				score += 2
			else:
				score += 1
		else:
			lose += 1
	score += 2 * min(lose, k)
	bridge = 0
	leave = 0
	for gap in tmp:
		if k >= gap:
			bridge += 1
			k -= gap
		else:
			leave += gap
	score += bridge
	return score
while t:
	t -= 1
	(n, k) = list(map(int, input().strip().split()))
	s = input()
	maxScore = cheatScore(s, n, k)
	print(maxScore)


import io
import os
from collections import Counter, defaultdict, deque

def makeRepeat(arr):
	repeat = [[arr[0], 0]]
	for x in arr:
		if x == repeat[-1][0]:
			repeat[-1][1] += 1
		else:
			repeat.append([x, 1])
	return repeat

def solve(N, K, S):
	if all((x == 'L' for x in S)):
		if K:
			return (min(N, K) - 1) * 2 + 1
		else:
			return 0
	repeats = makeRepeat(S)
	firstStreak = 0
	lastStreak = 0
	if repeats[-1][0] == 'L':
		lastStreak = repeats.pop()[1]
	if repeats and repeats[0][0] == 'L':
		firstStreak = repeats[0][1]
		repeats = repeats[1:]
	base = 0
	streaks = []
	for (ch, repeat) in repeats:
		if ch == 'L':
			streaks.append(repeat)
		else:
			base += (repeat - 1) * 2 + 1
	streaks.sort()
	total = 0
	for x in streaks:
		if x <= K:
			total += x * 2 + 1
			K -= x
		else:
			x = min(K, x)
			total += x * 2
			K -= x
	if K and lastStreak:
		x = min(K, lastStreak)
		total += x * 2
		K -= x
	if K and firstStreak:
		x = min(K, firstStreak)
		total += x * 2
		K -= x
	return base + total
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N, K) = [int(x) for x in input().split()]
	S = input().decode().rstrip()
	ans = solve(N, K, S)
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	ans = 0
	prev = 'L'
	for i in s:
		if i == 'W' and prev == 'W':
			ans += 2
		elif i == 'W':
			ans += 1
		prev = i
	temp = []
	a = 0
	b = 0
	x = 0
	y = 0
	for i in s:
		if i == 'W':
			break
		else:
			x += 1
	else:
		if k >= n:
			ans = 1 + 2 * (n - 1)
		else:
			ans = 1 + 2 * (k - 1)
		print(max(ans, 0))
		continue
	for i in s:
		if i == 'W':
			b = 1
			if a != 0:
				temp.append(a)
			a = 0
		elif b == 0:
			continue
		else:
			a += 1
	if a != 0:
		y = a
	temp = sorted(temp)
	for i in temp:
		if i <= k:
			ans += 2 * i + 1
			k -= i
		else:
			ans += 2 * k
			k = 0
	if k > 0:
		if x + y >= k:
			ans += 2 * k
		else:
			ans += 2 * (x + y)
	print(ans)


def solve():
	(n, k) = map(int, input().split())
	l = sorted(map(len, input().strip('L').split('W')))
	z = len(l) + k
	while l and l[0] <= k:
		k -= l.pop(0)
	ans = 2 * min(n, z - 1) - len(l)
	if ans <= 0:
		ans = 1
	print(ans - 1)
t = int(input())
for _ in range(0, t):
	solve()


t = int(input())
for inx in range(t):
	(n, k) = map(int, input().split())
	l = input()
	b = sc = 0
	g = []
	p = 'L'
	for c in l:
		if c == 'W':
			if p == 'W':
				sc += 2
			else:
				sc += 1
			p = 'W'
			if b:
				g.append(b)
			b = 0
		else:
			p = 'L'
			b += 1
	if b:
		g.append(b)
	cbg = cen = 0
	if l[0] == 'L':
		cbg = g.pop(0)
	if l[-1] == 'L':
		if sc:
			cen = g.pop()
	g.sort()
	while k and g:
		b = g.pop(0)
		if k >= b:
			k -= b
			sc += 2 * b + 1
		else:
			sc += 2 * k
			k = 0
	if k:
		if sc:
			sc += 2 * min(k, cbg + cen)
		else:
			sc += 2 * min(k, cbg) - 1
	print(sc)


import sys
input = sys.stdin.readline

def compress(string):
	string = string + '#'
	n = len(string)
	(begin, end, cnt) = (0, 1, 1)
	ans = []
	while end < n:
		if string[begin] == string[end]:
			(end, cnt) = (end + 1, cnt + 1)
		else:
			ans.append((string[begin], cnt))
			(begin, end, cnt) = (end, end + 1, 1)
	return ans
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()[:-1]
	s = compress(s)
	w_groups = 0
	w_cnt = 0
	l_cnt = 0
	li = []
	for (i, (char, cnt)) in enumerate(s):
		if char == 'W':
			w_groups += 1
			w_cnt += cnt
		if char == 'L':
			l_cnt += cnt
			if 1 <= i < len(s) - 1:
				li.append(cnt)
	if w_cnt == 0:
		print(max(min(k, l_cnt) * 2 - 1, 0))
		continue
	ans = w_cnt * 2 - w_groups
	ans += min(k, l_cnt) * 2
	li.sort()
	for val in li:
		if k >= val:
			ans += 1
			k -= val
	print(ans)


def solve(record, length, changes):
	if record == 'L' * length:
		return changes * 2 - 1 if changes > 0 else 0
	state = 'N'
	loss_runs = []
	win_runs = []
	counter = 0
	bonus = 0
	score = 0
	for i in record:
		if state == 'N':
			if i == 'L':
				bonus += 1
			else:
				state = 'W'
				counter += 1
		elif state == 'W':
			if i == 'W':
				counter += 1
			else:
				win_runs.append(counter)
				counter = 1
				state = 'L'
		elif i == 'L':
			counter += 1
		else:
			loss_runs.append(counter)
			counter = 1
			state = 'W'
	if state == 'W':
		win_runs.append(counter)
	else:
		bonus += counter
	for i in win_runs:
		score += 2 * i - 1
	loss_runs = sorted(loss_runs)
	for i in loss_runs:
		if changes >= i:
			score += 2 * i + 1
			changes -= i
		else:
			score += 2 * changes
			changes = 0
	if changes != 0:
		score += min(bonus * 2, changes * 2)
	return score
t = int(input())
for _ in range(t):
	(l, c) = [int(i) for i in input().split()]
	arr = input()
	print(solve(arr, l, c))


for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	s = input()
	chains = []
	chain = 0
	streak = False
	if k + s.count('W') >= n:
		print(2 * n - 1)
	elif k == 0 and s.count('W') == 0:
		print(0)
	else:
		for char in s.strip('L').strip('W'):
			if char == 'W' and chain != 0:
				chains.append(chain)
				chain = 0
			elif char == 'L':
				chain += 1
		if chain != 0:
			chains.append(chain)
		chains.sort()
		i = 0
		total = 0
		while chains and total + chains[i] <= k:
			total += chains[i]
			i += 1
			if i >= len(chains):
				break
		print(2 * (k + s.count('W')) - len(chains) - 1 + i)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	l = sorted(map(len, s.strip('L').split('W')))
	a = len(l) + k
	while l and l[0] <= k:
		k -= l.pop(0)
	print((2 * min(n, a - 1) - len(l) or 1) - 1)


import sys
input = sys.stdin.readline
t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	k = int(l[1])
	s = input()
	lfi = [i for i in s]
	ans = 0
	poss = 1
	for i in s:
		if i == 'W':
			poss = 0
			break
	if poss:
		print(max(2 * k - 1, 0))
		continue
	if s[0] == 'W':
		ans += 1
	for i in range(1, n):
		if s[i] == 'W' and s[i - 1] == 'W':
			ans += 2
		elif s[i] == 'W':
			ans += 1
	l = []
	start = 0
	end = -1
	done = 0
	ext1 = 0
	for i in range(n):
		if s[i] == 'L':
			ext1 += 1
		else:
			break
	for i in range(ext1, n):
		if done:
			if s[i] == 'W':
				l.append(end - start + 1)
				done = 0
			else:
				end += 1
		elif s[i] == 'L':
			start = i
			end = i
			done = 1
	ext = 0
	if done:
		ext = end - start + 1
	lfi = []
	for i in range(len(l)):
		lfi.append(l[i])
	lfi.sort()
	z = len(lfi)
	i = 0
	done1 = 0
	done2 = 0
	while i < z:
		if k == 0:
			break
		if k >= lfi[i]:
			k -= lfi[i]
			ans += 2 * lfi[i] + 1
			i += 1
		else:
			ans += 2 * k
			k = 0
			break
	ans += 2 * min(ext, k)
	k -= min(ext, k)
	if done1 == 0:
		if ext1 and k:
			ans += 2 * min(ext1, k)
	print(ans)


import sys
import random
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
input = sys.stdin.readline
getS = lambda : input().strip()
getN = lambda : int(input())
getList = lambda : list(map(int, input().split()))
getZList = lambda : [int(x) - 1 for x in input().split()]
INF = float('inf')
MOD = 10 ** 9 + 7
divide = lambda x: pow(x, MOD - 2, MOD)

def solve():
	(n, m) = getList()
	wl = getS()
	if 'W' not in wl:
		num = min(n, m)
		if num == 0:
			print(0)
		else:
			print(num * 2 - 1)
		return
	ans = 0
	prev = ''
	hashil = 0
	ishashi = True
	ct = 0
	cl = []
	for c in wl:
		if c == 'W':
			if prev == 'W':
				ans += 2
			else:
				if prev == 'L':
					if ishashi:
						hashil = ct
					else:
						cl.append(ct)
					ct = 0
				ans += 1
			ishashi = False
		else:
			ct += 1
		prev = c
	hashil += ct
	cl.sort()
	for cc in cl:
		if m >= cc:
			ans += cc * 2 + 1
			m -= cc
		else:
			ans += m * 2
			print(ans)
			return
	ans += min(hashil, m) * 2
	print(ans)
	return

def main():
	n = getN()
	for _ in range(n):
		solve()
	return
main()


for nt in range(int(input())):
	(n, k) = map(int, input().split())
	f = input()
	if 'W' not in f:
		if k != 0:
			print(1 + 2 * (k - 1))
		else:
			print(0)
		continue
	if f.count('L') <= k:
		print(1 + 2 * (n - 1))
		continue
	s = f.split('W')
	(start, end) = (s[0], s[-1])
	s.pop()
	s.pop(0)
	s.sort()
	ans = 0
	for i in s:
		if len(i) == 0:
			continue
		if len(i) <= k:
			ans += 2 * len(i) + 1
			k -= len(i)
		else:
			ans += 2 * k
			k = 0
	ans += k * 2
	for i in range(n):
		if f[i] == 'W':
			if i == 0 or f[i - 1] == 'L':
				ans += 1
			else:
				ans += 2
	print(ans)


from sys import stdin
input = stdin.readline
q = int(input())
for _ in range(q):
	(n, k) = map(int, input().split())
	s = input()
	if n == 1:
		if s.count('W') + k >= 1:
			print(1)
		else:
			print(0)
	else:
		s = s[:n]
		if s.count('L') == n:
			du = 2 * k - 1
			du = min(du, 2 * n - 1)
			if k == 0:
				du = 0
			print(du)
		else:
			k = min(k, s.count('L'))
			los = []
			count = 0
			for i in range(n):
				if s[i] == 'L':
					count += 1
				elif count > 0:
					los.append(count)
					count = 0
			if count > 0:
				los.append(count)
			if s[0] == 'L':
				los.pop(0)
			if s[-1] == 'L' and len(los) > 0:
				los.pop(-1)
			los.sort()
			win = []
			count = 0
			for i in range(n):
				if s[i] == 'W':
					count += 1
				elif count > 0:
					win.append(count)
					count = 0
			if count > 0:
				win.append(count)
			wyn = 0
			for x in win:
				wyn += 2 * x - 1
			wyk = 0
			i = 0
			while i < len(los) and wyk + los[i] <= k:
				wyn += 2 * (los[i] + 1) - 1
				wyk += los[i]
				i += 1
			dup = k - wyk
			wyn += dup * 2
			wyn = min(wyn, 2 * n - 1)
			print(wyn)


from collections import *
from itertools import *
from bisect import *

def inp():
	return int(input())

def arrinp():
	return [int(x) for x in input().split()]

def main():
	t = inp()
	for _ in range(t):
		(n, k) = arrinp()
		s = [x for x in input()]
		score = 0
		for i in range(n):
			if i == 0 and s[i] == 'W':
				score += 1
			elif s[i] == 'W' and s[i - 1] == 'W':
				score += 2
			elif s[i] == 'W' and s[i - 1] != 'W':
				score += 1
		if k == 0:
			print(score)
			continue
		if score == 0:
			print(1 + (k - 1) * 2)
			continue
		diff = []
		special = []
		last = -1
		i = 0
		while i < n:
			if s[i] == 'W':
				if last == -1:
					last = i
					if i > 0:
						special.append(i)
				else:
					if i - last - 1 > 0:
						diff.append(i - last - 1)
					last = i
			i += 1
		if n - last - 1 > 0:
			special.append(n - last - 1)
		diff.sort()
		for ele in diff:
			if ele <= k:
				score += 2 * ele + 1
				k -= ele
			elif ele > k:
				score += 2 * k
				k = 0
			if k == 0:
				break
		if k > 0:
			for ele in special:
				if ele <= k:
					score += 2 * ele
					k -= ele
				elif ele > k:
					score += 2 * k
					k = 0
				if k == 0:
					break
		print(score)
main()


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	s = [i for i in input()]
	if s.count('W') == 0:
		print(max(2 * k - 1, 0))
		continue
	if s[0] == 'W':
		ans = 1
	else:
		ans = 0
	for i in range(1, n):
		if s[i - 1] == 'W' and s[i] == 'W':
			ans += 2
		elif s[i - 1] == 'L' and s[i] == 'W':
			ans += 1
	beg = 0
	end = 0
	while s and s[-1] == 'L':
		end += 1
		s.pop()
	s.reverse()
	while s and s[-1] == 'L':
		beg += 1
		s.pop()
	s.reverse()
	cnt = []
	for i in range(1, len(s)):
		if s[i] == 'L' and s[i - 1] == 'W':
			cnt.append(1)
		elif s[i] == 'L' and s[i - 1] == 'L':
			cnt[-1] += 1
	cnt.sort()
	cnt.reverse()
	while k and cnt:
		if k >= cnt[-1]:
			k -= cnt[-1]
			ans += 2 * cnt[-1] + 1
			cnt.pop()
		else:
			ans += 2 * k
			k = 0
			cnt.pop()
	ans += 2 * min(k, end)
	k -= min(k, end)
	ans += 2 * min(k, beg)
	k -= min(k, beg)
	print(ans)


def solve(n, k, s):
	gaps = []
	first_w_index = -1
	last_w_index = -1
	score = 0
	win_streak = 0
	for i in range(n):
		if s[i] == 'W':
			win_streak += 1
			if first_w_index == -1:
				first_w_index = i
			elif i - last_w_index - 1 > 0:
				gaps.append(i - last_w_index - 1)
			last_w_index = i
		elif win_streak > 0:
			score += 2 * win_streak - 1
			win_streak = 0
	if win_streak > 0:
		score += 2 * win_streak - 1
	gaps.sort()
	rem = []
	for g in gaps:
		if g <= k:
			score += 2 * g + 1
			k -= g
		else:
			rem.append(g)
	if k > 0:
		if len(rem) > 0:
			score += 2 * k
		elif first_w_index == -1:
			score += 2 * k - 1
		else:
			score += 2 * min(k, first_w_index + n - last_w_index - 1)
	return score
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	s = input()
	print(solve(n, k, s))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(input())
	w = 0
	for x in s:
		if x == 'W':
			w += 1
	if k >= n - w:
		print(1 + (n - 1) * 2)
	else:
		a = -1
		b = -3
		for i in range(n):
			if s[i] == 'W':
				a = i
				break
		for i in range(n):
			if s[n - i - 1] == 'W':
				b = n - i - 1
				break
		prev = False
		holes = {}
		h = 0
		for i in range(a, b + 1):
			if s[i] == 'W':
				if h in holes:
					holes[h].append(i - 1)
				elif h > 0:
					holes[h] = [i - 1]
				h = 0
				if not prev:
					prev = True
			else:
				h += 1
				if prev:
					prev = False
		nums = {}
		sorted_keys_holes = sorted(holes.keys())
		for h in sorted_keys_holes:
			if h > k:
				break
			else:
				x = min(k // h, len(holes[h]))
				nums[h] = []
				for r in range(x):
					nums[h].append((holes[h][r] - h, holes[h][r]))
				k -= x * h
		for h in nums.keys():
			for r in nums[h]:
				(i, j) = r
				for l in range(i, j + 1):
					s[l] = 'W'
		c = 0
		prev = False
		for i in range(a, b + 1):
			if s[i] == 'W':
				if prev:
					c += 2
				else:
					c += 1
				prev = True
			else:
				prev = False
		if c > 0:
			print(c + 2 * k)
		elif k > 0:
			print(1 + 2 * (k - 1))
		else:
			print(0)


t = int(input())
arr = [0]
for i in range(t):
	(n, sm) = map(int, input().split())
	count = 0
	count1 = 0
	count2 = -2
	a = input()
	arr.clear()
	for j in range(n):
		if a[j] == 'W':
			count += 1
			count1 += 1
			if count2 + 1 == j:
				count1 += 1
			if count != 1 and count2 + 1 != j:
				arr.append(j - count2 - 1)
			count2 = j
	sm = min(sm, n - count)
	arr = sorted(arr)
	if count == 0:
		print(max(0, 2 * sm - 1))
	else:
		sz = len(arr)
		for k in range(sz):
			if sm >= arr[k]:
				count1 += 2 * arr[k] + 1
				sm -= arr[k]
			else:
				count1 += 2 * sm
				sm = 0
		print(count1 + 2 * sm)
		arr.clear()


t = int(input())
for _ in range(t):
	(n, k) = input().split()
	(n, k) = (int(n), int(k))
	s = input()
	ind = []
	if 'W' not in s:
		print(max(0, min(2 * n - 1, 2 * k - 1)))
		continue
	score = 0
	prev = 'L'
	ind = []
	for i in range(len(s)):
		if s[i] == 'W' and prev == 'W':
			score += 2
			ind.append(i)
		elif s[i] == 'W':
			score += 1
			ind.append(i)
		prev = s[i]
	gaps = []
	for i in range(len(ind) - 1):
		if ind[i + 1] - ind[i] > 1:
			gaps.append(ind[i + 1] - ind[i])
	gaps = sorted(gaps)
	j = 0
	while j < len(gaps) and k >= gaps[j] - 1:
		k -= gaps[j] - 1
		score += 2 * gaps[j] - 1
		j += 1
	print(min(2 * n - 1, score + 2 * k))


import sys
t = int(input())
while t > 0:
	t -= 1
	input = sys.stdin.readline()
	(n, k) = map(int, input.split())
	s = sys.stdin.readline()
	no_los = 0
	no_win = 0
	for i in range(len(s)):
		if s[i] == 'L':
			no_los += 1
		else:
			no_win += 1
	if no_los <= k:
		print(2 * n - 1)
	elif no_los == n:
		if k == 0:
			print(0)
		else:
			print(2 * k - 1)
	else:
		initial_score = 0
		if s[0] == 'W':
			initial_score += 1
		for i in range(1, n):
			if s[i] == 'W' and s[i - 1] == 'W':
				initial_score += 2
			elif s[i] == 'W':
				initial_score += 1
		mid_los_ar = []
		i = 0
		while s[i] == 'L':
			i += 1
		while s[i] == 'W':
			i += 1
		j = n - 1
		while s[j] == 'L':
			j -= 1
		while s[j] == 'W':
			j -= 1
		cur = -1
		value = 0
		for m in range(i, j + 1):
			if s[m] == 'W':
				if value != 0:
					mid_los_ar.append(value)
					value = 0
			else:
				value += 1
		if value != 0:
			mid_los_ar.append(value)
		mid_los_ar.sort()
		initial_score += 2 * k
		rem = 0
		total = 0
		for i in range(len(mid_los_ar)):
			total += mid_los_ar[i]
			if total <= k:
				rem += 1
			else:
				break
		initial_score += rem
		print(initial_score)


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, k) = map(int, input().split())
	S = input().strip()
	if not 'W' in S:
		if k == 0:
			print(0)
		else:
			print(min(n, k) * 2 - 1)
		continue
	LIST = [[S[0], 0]]
	for s in S:
		if s == LIST[-1][0]:
			LIST[-1][1] += 1
		else:
			LIST.append([s, 1])
	if LIST[0][0] == 'L':
		F = LIST.pop(0)
		F = F[1]
	else:
		F = -1
	if LIST and LIST[-1][0] == 'L':
		L = LIST.pop()
		L = L[1]
	else:
		L = -1
	ANS = 0
	LS = []
	for (x, y) in LIST:
		if x == 'W':
			ANS += y * 2 - 1
		else:
			LS.append(y)
	LS.sort()
	for ls in LS:
		if k >= ls:
			k -= ls
			ANS += ls * 2 + 1
		else:
			ANS += k * 2
			k = 0
	if L != -1:
		if k >= L:
			ANS += 2 * L
			k -= L
		else:
			ANS += k * 2
			k = 0
	if F != -1:
		if k >= F:
			ANS += 2 * F
		else:
			ANS += 2 * k
	print(ANS)


for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	s = input()
	s2 = s.strip('L')
	Ls = len(s) - len(s2)
	chains = []
	chain = 0
	score = 0
	streak = False
	for char in s2:
		if char == 'W':
			if streak:
				score += 2
			else:
				score += 1
				streak = True
		else:
			streak = False
	for char in s2.strip('W'):
		if char == 'W' and chain != 0:
			chains.append(chain)
			chain = 0
		elif char == 'L':
			chain += 1
	if chain != 0:
		chains.append(chain)
	chains.sort()
	i = 0
	while chains and k >= chains[i]:
		k -= chains[i]
		score += 2 * chains[i] + 1
		i += 1
		if i >= len(chains):
			break
	Ls += sum(chains[i:])
	if k:
		if k > Ls:
			score += 2 * Ls
		elif 'W' in s:
			score += 2 * k
		else:
			score += 2 * k - 1
	print(score)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	if 'W' not in s:
		ans = min(n, k) * 2 - 1
		print(max(ans, 0))
	else:
		extra = 0
		i = 0
		while i < n and s[i] == 'L':
			i += 1
		extra = i
		j = n - 1
		while j >= 0 and s[j] == 'L':
			j -= 1
			extra += 1
		c = []
		while i <= j:
			if s[i] == 'W':
				i += 1
			else:
				m = 0
				while i <= j and s[i] == 'L':
					m += 1
					i += 1
				c.append(m)
		c.sort()
		ans = 0
		i = 0
		while i < n:
			if s[i] == 'W':
				ans += 1
				i += 1
				while i < n and s[i] == 'W':
					i += 1
					ans += 2
			else:
				i += 1
		for j in c:
			if k >= j:
				ans += j * 2 + 1
				k -= j
			else:
				ans += k * 2
				k = 0
				break
		ans += min(k, extra) * 2
		print(ans)


from sys import stdin
T = int(stdin.readline().strip())
for caso in range(T):
	(n, k) = map(int, stdin.readline().strip().split())
	s = list(stdin.readline().strip())
	aux = []
	last = -1
	for i in range(n):
		if i > 0 and s[i] == 'L' and (s[i - 1] == 'W'):
			last = i
		if i < n - 1 and s[i] == 'L' and (s[i + 1] == 'W') and (last != -1):
			aux.append([i - last, last, i])
	aux.sort()
	for i in aux:
		for j in range(i[1], i[2] + 1):
			if k > 0:
				s[j] = 'W'
				k -= 1
	ini = -1
	fin = n
	for i in range(n):
		if s[i] == 'W':
			ini = i - 1
			break
	for i in range(n - 1, -1, -1):
		if s[i] == 'W':
			fin = i + 1
			break
	for i in range(ini, -1, -1):
		if k > 0:
			s[i] = 'W'
			k -= 1
	for i in range(fin, n):
		if k > 0:
			s[i] = 'W'
			k -= 1
	ans = 0
	if ini == -1 and fin == n:
		for i in range(n):
			if k > 0:
				s[i] = 'W'
				k -= 1
	for i in range(n):
		if s[i] == 'W':
			if i > 0 and s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = 1
	X = []
	ans = 0
	y = 0
	for s in input():
		if s == 'W':
			y = 1
			if x:
				X += [x]
				ans += 1
				x = 0
			else:
				ans += 2
		else:
			x += 1
	if y == 0:
		print(max(min(k, n) * 2 - 1, 0))
		continue
	if x:
		X += [x + 10 ** 8]
	X[0] += 99999999
	X.sort()
	X.reverse()
	while k > 0 and X:
		x = X.pop()
		if x >= 10 ** 7:
			x -= 10 ** 8
			ans += 2 * min(x, k)
			k -= min(x, k)
		elif x > k:
			ans += 2 * k
			break
		else:
			ans += 2 * x + 1
			k -= x
	print(ans)


(z, zz) = (input, lambda : list(map(int, z().split())))
fast = lambda : stdin.readline().strip()
zzz = lambda : [int(i) for i in stdin.readline().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
import sys, io, os
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)

def solve(n, k, s):
	arr = []
	sm = 0
	if 'W' not in s:
		return max(min(n, k) * 2 - 1, 0)
	arr = s.split('W')[1:-1]
	arr = list(filter(None, arr))
	arr = [len(i) for i in arr]
	arr.sort()
	sm = s.count('W')
	ncut = len(arr) + 1
	for i in range(len(arr)):
		if k >= arr[i]:
			sm += arr[i]
			k -= arr[i]
			ncut -= 1
	return max(0, min(2 * n - 1, (sm + k) * 2 - ncut))
t = int(input())
for x in range(t):
	(n, k) = zz()
	s = fast()
	h = solve(n, k, s)
	print(h)


for _ in range(int(input())):
	(n, x) = map(int, input().split())
	l = list(input())
	t = []
	temp = x
	c = 0
	m = 0
	s = 0
	f = 0
	m2 = 0
	e = 0
	for i in range(1, n):
		if l[i] == 'W':
			if l[i - 1] == 'W':
				s += 2
			else:
				s += 1
	if l[0] == 'W':
		s += 1
	for i in range(n):
		if l[i] == 'L':
			if i == 0:
				f = 1
			c += 1
		else:
			if c != 0 and f == 0:
				t.append(c)
			if f == 1:
				m2 = c
			c = 0
			f = 0
	if c != 0:
		if f == 1:
			e = 1
			m2 = c
		else:
			m = c
			c = 0
	t.sort()
	for i in t:
		if x >= i:
			s += 2 * i
			s += 1
			x -= i
		else:
			s += 2 * x
			x -= x
	if x != 0 and m != 0:
		if x >= m:
			s += 2 * m
			x -= m
		else:
			s += 2 * x
			x -= x
	if x != 0 and m2 != 0:
		if x >= m2:
			s += 2 * m2
			x -= m2
		else:
			s += 2 * x
			x -= x
	if e == 1:
		if temp != 0:
			print(2 * (temp - 1) + 1)
		else:
			print(0)
	else:
		print(s)


def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		l = list(input())
		segments = []
		previous_w = -1
		first_w = n
		last_w = -1
		for (c, el) in enumerate(l):
			if el == 'W':
				if previous_w != -1 and c != previous_w + 1:
					segments.append((c - previous_w - 1, previous_w, c))
				previous_w = c
				first_w = min(first_w, c)
				last_w = max(last_w, c)
		segments.sort()
		z = 0
		while z < len(segments):
			current_segment = segments[z]
			z += 1
			for i in range(min(k, current_segment[0])):
				l[current_segment[1] + i + 1] = 'W'
			k -= current_segment[0]
			if k <= 0:
				break
		if k > 0:
			for j in range(min(first_w, k)):
				l[first_w - j - 1] = 'W'
		k -= first_w
		if k > 0 and first_w != n:
			for x in range(min(n - last_w - 1, k)):
				l[last_w + x + 1] = 'W'
		total = 0
		dub = False
		for (c, el) in enumerate(l):
			if el == 'W':
				total += 1 + dub
			dub = el == 'W'
		print(total)
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	S = input()
	K = k
	s = []
	for i in S:
		s.append(i)
	a = []
	if s[0] == 'L':
		ans = 0
	else:
		ans = 1
	for i in range(1, n):
		if s[i] == 'W':
			ans += 1
			if s[i - 1] == 'W':
				ans += 1
	cnt = 0
	for i in range(n):
		if s[i] == 'L':
			cnt += 1
		else:
			if cnt != 0:
				a.append(cnt)
			cnt = 0
	if cnt != 0:
		a.append(cnt)
	if len(a) != 0 and s[0] == 'L':
		a.remove(a[0])
	if len(a) != 0 and s[-1] == 'L':
		a.remove(a[-1])
	mx = a.count(0)
	a.sort()
	for i in a:
		if i <= k:
			k -= i
			ans += 1 + 2 * i
		else:
			ans += 2 * k
			k = 0
			break
	cnt = 0
	for i in range(n - 1, -1, -1):
		if s[i] == 'L':
			cnt += 1
		else:
			break
	mn = min(k, cnt)
	k -= mn
	ans += 2 * mn
	cnt = 0
	for i in range(n):
		if s[i] == 'L':
			cnt += 1
		else:
			break
	mn = min(k, cnt)
	ans += 2 * mn
	if s.count('W') == 0:
		mn = min(K, n)
		if mn >= 1:
			ans = 1 + 2 * (mn - 1)
	print(ans)


def score(a, n):
	score = 0 if a[0] == 'L' else 1
	for i in range(1, n):
		if a[i] == a[i - 1] == 'W':
			score += 2
		elif a[i] == 'W':
			score += 1
	return score
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	mylist = []
	x = 0
	while x < n and s[x] == 'L':
		x += 1
	count = 0
	while x < n:
		if s[x] == 'W':
			if count != 0:
				mylist.append(count)
				count = 0
		else:
			count += 1
		x += 1
	mylist.sort()
	ans = 0
	for i in mylist:
		k -= i
		if k == 0:
			ans += 2 * i + 1
			break
		elif k > 0:
			ans += 2 * i + 1
		else:
			ans += 2 * i
			break
	counter = 0
	while counter < n and s[counter] == 'L':
		counter += 1
	scounter = 0
	while scounter < n and s[n - 1 - scounter] == 'L':
		scounter += 1
	ans += score(s, n)
	if ans == 0 and k > 0:
		ans -= 1
	if k <= scounter + counter:
		ans += 2 * k
	else:
		ans += 2 * (scounter + counter)
	print(ans)


import sys
input = sys.stdin.readline
import math

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])
T = inp()
t = 0
while t < T:
	t += 1
	(n, k) = inlt()
	x = insr()
	res = 0
	arr = []
	gap = -1
	flag = False
	for c in x:
		if c == 'L' and gap != -1:
			gap += 1
		elif c == 'W':
			flag = True
			if gap == -1:
				gap = 0
				continue
			if gap != 0:
				arr.append(gap)
				gap = 0
	if not flag and k > 0:
		print(min(k, len(x)) * 2 - 1)
		continue
	arr.sort()
	for gap in arr:
		if k >= gap:
			res += gap * 2 + 1
			k -= gap
		else:
			res += k * 2
			k = 0
			break
	if k > 0:
		start = 0
		while start < len(x) and x[start] == 'L':
			start += 1
		end = 0
		while end < len(x) and len(x) - end - 1 > start and (x[len(x) - end - 1] == 'L'):
			end += 1
		if start > 0 or end > 0:
			if k > start + end:
				res += (start + end) * 2
			else:
				res += k * 2
	prior = 0
	if x[0] == 'W':
		prior += 1
	for i in range(1, len(x)):
		if x[i] == 'W':
			if x[i - 1] == 'W':
				prior += 2
			else:
				prior += 1
	res += prior
	print(res)


import sys

def sol(n, k, s):
	a = sorted(map(len, s.strip('L').split('W')))
	m = len(a) + k
	while a and a[0] <= k:
		k -= a.pop(0)
	return (2 * min(n, m - 1) - len(a) or 1) - 1

def main():
	f = sys.stdin
	t = int(f.readline())
	for _ in range(t):
		(n, k) = map(int, f.readline().split())
		s = f.readline().strip()
		print(sol(n, k, s))
main()


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	s = input()
	scoreinitial = 0
	if s[0] == 'W':
		scoreinitial += 1
	for i in range(1, len(s)):
		if s[i] == 'W' and s[i - 1] == 'W':
			scoreinitial += 2
		elif s[i] == 'W':
			scoreinitial += 1
	paq = []
	cuts = s.split('W')
	extr = [len(x) for x in cuts]
	nbL = sum(extr)
	stock = min(m, nbL)
	if stock == 0:
		print(scoreinitial)
	elif nbL < n:
		paq = sorted(extr[1:-1])
		rep = 0
		for i in paq:
			if i <= stock and i > 0:
				rep += i * 2 + 1
				stock -= i
		rep += 2 * stock
		print(rep + scoreinitial)
	else:
		print(stock * 2 - 1)


from sys import *
from math import *
from bisect import *
t = int(stdin.readline())
for _ in range(t):
	(n, k) = map(int, stdin.readline().split())
	s = input()
	c = []
	f = 0
	w = 0
	l = 0
	for i in range(n):
		if s[i] == 'W':
			w += 1
		else:
			l += 1
	for i in range(n):
		if s[i] == 'W' and f == 0:
			f = 1
			j = i
		elif f == 1 and s[i] == 'W':
			c.append(i - j - 1)
			j = i
	d = []
	for i in range(len(c)):
		if c[i] != 0:
			d.append(c[i])
	ans = 0
	d.sort()
	for i in range(len(d)):
		if d[i] <= k:
			k -= d[i]
			ans += 2 * (d[i] - 1) + 3
			l -= d[i]
		else:
			break
	for i in range(n):
		if s[i] == 'W':
			if i == 0:
				ans += 1
			elif s[i - 1] == 'L':
				ans += 1
			else:
				ans += 2
	ans += min(k, l) * 2
	if w == 0 and k > 0:
		ans -= 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	s = input()
	if s.count('L') == len(s):
		if k:
			score = min(k - 1, len(s) - 1) * 2 + 1
		else:
			score = 0
		print(score)
		continue
	f = False
	lc = 0
	totl = 0
	d = []
	score = 0
	for (p, i) in enumerate(s):
		if i == 'L':
			lc += 1
			totl += 1
		else:
			if lc:
				if f:
					d.append(lc)
				lc = 0
			f = True
			if p and s[p - 1] == 'W':
				score += 2
			else:
				score += 1
	d.sort(reverse=True)
	while d:
		if k >= d[-1]:
			totl -= d[-1]
			k -= d[-1]
			score += 1 + 2 * d[-1]
			d.pop()
		else:
			break
	score += min(totl, k) * 2
	print(score)


for t in range(int(input())):
	(n, k) = map(int, input().split())
	a = input()
	b = [0] * n
	s = 0
	c = 0
	w = a.count('W')
	if k >= n - w:
		print(2 * n - 1)
	elif w == 0:
		print(max(0, 2 * k - 1))
	else:
		f = a.find('W')
		for i in range(f, n):
			if a[i] == 'W':
				s += 1
				if i > 0 and a[i - 1] == 'W':
					s += 1
				b[c] += 1
				c = 0
			else:
				c += 1
		for j in range(1, n):
			if k >= j * b[j]:
				s += b[j] * (2 * j + 1)
				k -= j * b[j]
			else:
				m = k // j
				r = k % j
				s += m * (2 * j + 1) + 2 * r
				k = 0
				break
		s += 2 * k
		print(s)


import sys, math
input = sys.stdin.readline
t = int(input())
for r in range(t):
	(n, k) = map(int, input().split())
	s = input().strip('\n')
	ans = 0
	l = []
	for i in s:
		l.append(i)
	intervals = []
	i = 0
	left = []
	right = []
	while i < n:
		if l[i] == 'W':
			i += 1
			continue
		else:
			current = [i, i]
			while i < n and l[i] == 'L':
				i += 1
			current[1] = i
			if current[0] == 0:
				left.append(current)
			elif current[1] == n:
				right.append(current)
			else:
				intervals.append(current)
	intervals.sort(key=lambda x: abs(x[0] - x[1]))
	for interval in intervals:
		for i in range(interval[0], interval[1]):
			if k > 0:
				l[i] = 'W'
				k -= 1
	try:
		int1 = left[0]
		for i in range(int1[1] - 1, int1[0] - 1, -1):
			if k > 0:
				l[i] = 'W'
				k -= 1
	except:
		pass
	try:
		int2 = right[0]
		for i in range(int2[0], int2[1]):
			if k > 0:
				l[i] = 'W'
				k -= 1
	except:
		pass
	for i in range(n):
		if l[i] == 'W':
			if i == 0 or l[i - 1] == 'L':
				ans += 1
			else:
				ans += 2
	print(ans)


def calculate(game):
	if not game:
		return 0
	su = 1 if game[0] == 'W' else 0
	prev = game[0]
	for g in game[1:]:
		if g == 'W':
			su += 2 if prev == 'W' else 1
			prev = 'W'
		else:
			prev = 'L'
	return su
for t in range(int(input())):
	(n, k) = map(int, input().split())
	games = input()
	gaps = list(map(len, games.split('W')))
	front_end = []
	bonus = 0
	if len(gaps):
		front_end.append(gaps.pop(0))
	if len(gaps):
		front_end.append(gaps.pop())
	else:
		bonus = -1 if k else 0
	front_end = [f for f in front_end if f]
	front_end.sort()
	gaps = [g for g in gaps if g]
	gaps.sort()
	while k:
		midgap = 0
		if gaps:
			top = gaps.pop(0)
			midgap = 1
		elif front_end:
			top = front_end.pop(0)
		else:
			break
		if top > k:
			bonus += k * 2
			k = 0
		else:
			bonus += top * 2 + midgap
			k -= top
	print(calculate(games) + bonus)


t = int(input())
for t_ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	gaps = [len(x) for x in s.split('W') if len(x) > 0]
	runs = [len(x) for x in s.split('L') if len(x) > 0]
	ends = 0
	if s[0] == 'L':
		ends += gaps[0]
		del gaps[0]
	if s[-1] == 'L' and len(gaps) > 0:
		ends += gaps[-1]
		del gaps[-1]
	gaps.sort()
	i = 0
	while k > 0 and i < len(gaps):
		if gaps[i] <= k:
			k -= gaps[i]
			gaps[i] = 0
			i += 1
		else:
			gaps[i] -= k
			k = 0
	new_gaps = [g for g in gaps if g > 0]
	if k > 0 and ends > 0:
		if ends >= k:
			ends -= k
		else:
			ends = 0
	score = (n - sum(new_gaps) - ends) * 2 - (len(new_gaps) + 1)
	score = max(score, 0)
	print(score)


from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 998244353
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')

def solve():
	for _ in range(ii()):
		(n, k) = mi()
		s = si()
		a = []
		c = 0
		ans = 0
		if s[0] == 'W':
			a.append(0)
			ans += 1
		else:
			c += 1
		for i in range(1, n):
			if s[i] == 'W':
				if c > 0:
					a.append(c)
				c = 0
				if s[i - 1] == 'W':
					ans += 2
				else:
					ans += 1
			else:
				c += 1
		a.append(c)
		if len(a) >= 2:
			b = a[1:]
			b.pop()
			b.sort()
			for i in b:
				if i > k:
					ans += 2 * k
					k = 0
					break
				else:
					ans += 2 * i
					ans += 1
					k -= i
		if ans == 0:
			ans -= 1
		x = min(k, a[0])
		ans += 2 * x
		k -= x
		x = min(k, a[-1])
		ans += 2 * x
		if n == 1:
			ans = min(ans, 1)
		print(max(ans, 0))
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
solve()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
for _ in range(N()):
	(n, k) = RL()
	s = input().strip()
	if 'W' not in s:
		print(max(0, k * 2 - 1))
	else:
		t = s.find('W')
		l = []
		w = []
		now = 0
		ww = 0
		for i in range(t, n):
			if s[i] == 'W':
				if now > 0:
					l.append(now)
					now = 0
				ww += 1
			else:
				if ww > 0:
					w.append(ww)
					ww = 0
				now += 1
		if ww > 0:
			w.append(ww)
		res = 0
		for i in w:
			res += i * 2 - 1
		tail = now
		l.sort()
		for i in l:
			if i > k:
				res += 2 * k
				k = 0
				break
			else:
				k -= i
				res += 2 * i + 1
		res += min(k, tail) * 2
		k = max(0, k - tail)
		res += min(t, k) * 2
		print(res)


import sys, math, cmath, time, collections
start_time = time.time()

def solve():
	(n, k) = invr()
	s = list(insr())
	ww = 0
	if 'W' not in s:
		if k == 0:
			c = 0
		else:
			c = 2 * min(k, len(s)) - 1
	elif s.count('W') == 1:
		if k == 0:
			c = 1
		else:
			c = 2 * min(k + 1, len(s)) - 1
	else:
		q = s.index('W')
		s.reverse()
		w = s.index('W')
		s.reverse()
		c = 0
		qw = []
		for i in range(q, len(s) - w):
			if s[i] == 'L':
				c = c + 1
			elif c > 0:
				qw.append(c)
				c = 0
		qw.sort(reverse=True)
		ww = 0
		while qw and k > 0:
			qq = qw.pop()
			if k >= qq:
				k = k - qq
				ww = ww + qq * 2 + 1
			else:
				ww = ww + k * 2
				k = 0
		ww = ww + k * 2
		c = 0
		for i in range(len(s)):
			if s[i] == 'W':
				if i != 0 and s[i - 1] == 'W':
					c = c + 2
				else:
					c = c + 1
	print(min(2 * len(s) - 1, c + ww))

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(1, t + 1):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

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

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

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def power_two(x):
	return x and (not x & x - 1)

def ceil(a, b):
	return -(-a // b)

def seive(n):
	a = [1]
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p ** 2, n + 1, p):
				prime[i] = False
		p = p + 1
	for p in range(2, n + 1):
		if prime[p]:
			a.append(p)
	return a
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


def cheat(n, k, origames):
	kk = k
	(Llis, Wlis) = (origames.split('W'), origames.split('L'))
	Wlis = sorted(Wlis, key=lambda x: len(x))
	if Wlis[-1] == '':
		if 2 * k - 1 >= 0:
			return 2 * k - 1
		else:
			return 0
	if k >= origames.count('L'):
		return 2 * len(origames) - 1
	else:
		Llis.pop(0)
		Llis.pop(-1)
		Llis = sorted(Llis, key=lambda x: len(x))
		link = 0
		for i in range(len(Llis)):
			if Llis[i] != '':
				if len(Llis[i]) <= k:
					k -= len(Llis[i])
					link += 1
				else:
					break
		score = 0
		for j in range(len(Wlis)):
			if len(Wlis[j]) >= 1:
				score += 2 * len(Wlis[j]) - 1
		score += 2 * kk + link
		return score
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	origames = input()
	print(cheat(n, k, origames))


from collections import deque
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	st = input()
	side = []
	mid = []
	tmp = 0
	ans = 0
	for a in range(n):
		if st[a] == 'W':
			if tmp != 0:
				mid.append(tmp)
				tmp = 0
				ans += 1
			elif a == 0:
				ans += 1
			else:
				ans += 2
		else:
			tmp += 1
	if tmp != 0:
		side.append(tmp)
	if st[0] == 'L' and len(mid) > 0:
		side.append(mid[0])
		mid = mid[1:]
	if ans == 0 and k >= 1:
		print(2 * min(k, len(st)) - 1)
		continue
	mid.sort()
	side.sort()
	midq = deque(mid)
	sideq = deque(side)
	while k > 0:
		if len(midq) > 0 and midq[0] <= k:
			tmp = midq.popleft()
			ans += 2 * tmp + 1
		else:
			if len(midq) == 0 and len(sideq) == 0:
				break
			elif len(midq) == 0:
				tmp = sideq.popleft()
			elif len(sideq) == 0:
				tmp = midq.popleft()
			else:
				tmp = sideq.popleft()
			ans += 2 * min(tmp, k)
		k -= tmp
	print(ans)


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	(n, k) = MI()
	s = list(SI())
	cur = 0
	a = 0
	b = 0
	d = []
	temp = 0
	if len(set(s)) == 1 and 'L' in s and (k > 0):
		k -= 1
		s[0] = 'W'
	for i in range(n):
		if s[i] == 'W':
			if temp != 0:
				d.append(temp)
				temp = 0
			if i > 0 and s[i - 1] == 'W':
				cur += 2
			else:
				cur += 1
		else:
			temp += 1
	if temp != 0:
		d.append(temp)
	if 'L' not in s or k == 0:
		print(cur)
	else:
		if s[0] == 'L':
			a = d[0]
			d = d[1:]
		if s[-1] == 'L':
			a += d[-1]
			d = d[:-1]
		d.sort()
		for i in range(len(d)):
			if k >= d[i]:
				cur += d[i] * 2 + 1
				k -= d[i]
			else:
				cur += k * 2
				k = 0
			if k == 0:
				break
		if k != 0:
			m = min(k, a)
			if m > 0:
				k -= m
				cur += m * 2
		print(cur)


def solve():
	(n, m) = map(int, input().split())
	s = input()
	s = s[:n]
	p = 0
	gaps = []
	points = 0
	lastsect = 0
	firstsect = 0
	wins = len(list(filter(lambda x: x == 'W', s)))
	if wins == 0:
		m = min(m, n)
		if m == 0:
			print(0)
		else:
			print(2 * m - 1)
		return
	if m + wins >= n:
		print(2 * n - 1)
		return
	i = 0
	while i < n and s[i] == 'L':
		i += 1
	firstsect = i
	for (j, v) in enumerate(s[i:]):
		if v == 'L':
			p += 1
		else:
			if p > 0:
				gaps.append(p)
				p = 0
			points += 1 + (1 if j + i > 0 and s[j + i - 1] == 'W' else 0)
	if p > 0:
		lastsect = p
	gaps.sort()
	i = 0
	k = m
	while i < len(gaps) and k > 0:
		if gaps[i] > k:
			points += 2 * k
			k = 0
		else:
			points += 2 * gaps[i] + 1
			k -= gaps[i]
		i += 1
	points += 2 * min(k, firstsect)
	k -= min(k, firstsect)
	points += 2 * min(k, lastsect)
	print(points)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(input())
	ind = []
	ans = 0
	for i in range(n):
		if s[i] == 'W':
			ind.append(i)
			if i - 1 >= 0 and s[i - 1] == 'W':
				ans += 1
			ans += 1
	if k == 0:
		print(ans)
	elif len(ind) == 0:
		print(min(k, n) * 2 - 1)
	else:
		gap = []
		for i in range(len(ind) - 1):
			gap.append(ind[i + 1] - ind[i] - 1)
		gap.sort()
		k = min(k, n - len(ind))
		ans += 2 * k
		for i in gap:
			if i > 0:
				if k >= i:
					ans += 1
					k -= i
				else:
					break
		print(ans)


import sys
import heapq
import copy
import math
import decimal
input = sys.stdin.readline

def binary_exponentiation(a, b):
	ans = 1
	while b != 0:
		bit = b % 2
		if bit == 1:
			ans = ans * a
		a = a * a
		b = b // 2
	return ans

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	s = list(s[:len(s) - 1])
	s = [ord(s[i]) - ord('a') for i in range(len(s))]
	return s

def invr():
	return map(int, input().split())
ans = 0

def pr_list(a):
	print(*a, sep=' ')

def swap(a, b):
	temp = a
	a = b
	b = temp
	return [a, b]

def pri(a, b):
	s = '? ' + str(a) + ' ' + str(b)
	print(s)
	sys.stdout.flush()
result = []

def nCk(arr, itr, k, n):
	if len(arr) == k:
		result.append(arr)
		return
	if len(arr) > k or itr == n + 1:
		return
	nCk(arr + [itr], itr + 1, k, n)
	nCk(arr, itr + 1, k, n)
	return

def nPk(arr, itr, k, n):
	if len(arr) == k:
		result.append(arr)
		return
	if len(arr) > k or itr == n + 1:
		return
	for i in range(len(arr) + 1):
		nPk(arr[0:i] + [itr] + arr[i:len(arr)], itr + 1, k, n)
	nPk(arr, itr + 1, k, n)
	return

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	stack = []
	arr = []
	heapq.heapify(arr)
	for test in range(tests):
		(n, k) = inlt()
		s = insr()
		change = []
		left = 0
		start = 0
		for i in range(n):
			if s[i] == 'W':
				start = i
				break
			left = left + 1
		pre = start
		for i in range(start, n):
			if s[i] == 'W':
				if i - pre > 0:
					change.append([i - pre - 1, pre + 1, i - 1])
				pre = i
		change.sort()
		for m in change:
			[val, i, j] = m
			for n in range(i, j + 1):
				if k == 0:
					break
				s[n] = 'W'
				k = k - 1
			if k == 0:
				break
		for m in range(start - 1, -1, -1):
			if k == 0:
				break
			s[m] = 'W'
			k = k - 1
		for m in range(0, len(s)):
			if k == 0:
				break
			if s[m] == 'L':
				s[m] = 'W'
				k = k - 1
		score = 0
		streak = 0
		for i in s:
			if i == 'W':
				if streak == 1:
					score = score + 2
				else:
					score = score + 1
				streak = 1
			else:
				streak = 0
		print(score)
main()


for w in range(int(input())):
	(n, k) = tuple(map(int, input().split()))
	s = str(input())
	if k == n:
		print(1 + 2 * (n - 1))
	elif n == 1 and k > 0:
		print(1)
	elif n == 1 and k == 0:
		if s[0] == 'W':
			print(1)
		else:
			print(0)
	elif k >= s.count('L'):
		print(1 + 2 * (n - 1))
	else:
		ans = 0
		t1 = 0
		l = []
		for i in range(n):
			if s[i] == 'W':
				if i == 0 or s[i - 1] != 'W':
					ans += 1
				else:
					ans += 2
		i = 0
		while i < n:
			if s[i] == 'L':
				if i == 0:
					while i < n and s[i] == 'L':
						t1 += 1
						i += 1
				elif i == n - 1:
					t1 += 1
					i += 1
				else:
					x = 0
					while i < n and s[i] == 'L':
						x += 1
						i += 1
					if i != n:
						l.append(x)
					else:
						t1 += x
			else:
				i += 1
		if k == 0:
			print(ans)
		elif ans == 0:
			print(1 + 2 * max(k - 1, 0))
		elif k >= sum(l):
			print(ans + 2 * k + len(l))
		else:
			l = sorted(l)
			x = 0
			for i in range(len(l)):
				x += l[i]
				if x > k:
					break
			print(ans + 2 * k + i)


from math import inf

def put():
	return map(int, input().split())
t = int(input())
for _ in range(t):
	(n, k) = put()
	l = [1 if i == 'W' else 0 for i in list(input())]
	s = sum(l)
	if s + k >= n:
		print(2 * n - 1)
		continue
	elif s == 1:
		print(2 * min(n - 1, k) + 1)
		continue
	elif s == 0:
		print(max(2 * k - 1, 0))
		continue
	ind = []
	prev = -inf
	for i in range(n):
		if l[i] == 1:
			ind.append(i - prev - 1)
			prev = i
	if ind:
		ind.sort()
	for d in ind:
		if d <= k:
			s += 2 * d + 1
			k -= d
	if k > 0:
		s += 2 * k
	print(s)


for j in range(int(input())):
	(n, k) = map(int, input().split())
	r = input()
	a = []
	t = r[0]
	s = 1
	for i in range(1, n):
		if r[i] == t:
			s += 1
		else:
			a.append([t, s])
			t = r[i]
			s = 1
	a.append([t, s])
	b = []
	h = len(a)
	s = 0
	m = 0
	t = 0
	if a[0][0] == 'L':
		s = 1
	if a[-1][0] == 'L':
		h -= 1
	for i in range(s, h):
		if a[i][0] == 'W':
			m += a[i][1]
			t += 1
		else:
			b.append(a[i][1])
	b.sort()
	i = 0
	s = 0
	while i < len(b) and s + b[i] <= k:
		t -= 1
		s += b[i]
		i += 1
	m += s
	if i < len(b) and s < k:
		m += k - s
	elif i == len(b) and s < k:
		f = 0
		if a[0][0] == 'L':
			f += a[0][1]
		if a[-1][0] == 'L':
			f += a[-1][1]
		if m == 0:
			t = 1
		m += min(k - s, f)
	print(2 * m - t)


ns = lambda : input()
ni = lambda : int(input())
nm = lambda : map(int, input().split())
nl = lambda : list(map(int, input().split()))
for _ in range(ni()):
	(n, k) = nm()
	s = ns()
	w = []
	l = []
	i = count = 1
	f = s[0]
	ll = []
	while i < n:
		if s[i] == 'W' and f != 'W':
			l.append(count)
			ll.append(count)
			w.append(0)
			f = 'W'
			count = 1
		elif s[i] == 'L' and f != 'L':
			w.append(count)
			l.append(0)
			f = 'L'
			count = 1
		else:
			count += 1
		i += 1
	if s[-1] == 'W':
		w.append(count)
		l.append(0)
	else:
		l.append(count)
		ll.append(count)
		w.append(0)
	if n < 3:
		ans = min(sum(w) + k, n)
		if ans != 0:
			ans = 2 * ans - 1
		print(ans)
		continue
	z = []
	if k >= sum(ll):
		print(2 * n - 1)
		continue
	if l[0] != 0 and len(ll) > 0:
		t = ll.pop(0)
		z.append(t)
	if l[-1] != 0 and len(ll) > 0:
		t = ll.pop(-1)
		z.append(t)
	ll.sort()
	su = 0
	ind = 0
	if k == 0:
		ans = sum(w)
		if ans != 0:
			ans = 2 * ans - 1 - len(ll)
		print(ans)
		continue
	while ind < len(ll):
		su += ll[ind]
		if su == k:
			ind += 1
			break
		elif su > k:
			su -= ll[ind]
			break
		ind += 1
	if ind == len(l):
		ans = min(n, sum(w) + k)
		ans = 2 * ans - 1
	else:
		ans = min(n, sum(w) + k)
		ans = 2 * ans - 1 - (len(ll) - ind)
	print(ans)


def find_consecutive_lose_rounds(match_log):
	lose_sections_length = []
	start_winning = False
	length = 0
	original_point = 0
	for i in range(len(match_log)):
		char = match_log[i]
		if char == 'L':
			length += 1
			start_winning = False
		else:
			if start_winning:
				original_point += 2
			else:
				original_point += 1
				if length > 0:
					lose_sections_length.append(length)
			start_winning = True
			length = 0
	return (lose_sections_length, original_point)

def remove_head_tail_losing_streak(match_log):
	head_length = 0
	tail_length = 0
	head_tail_length = 0
	is_full_loses = False
	for i in range(len(match_log)):
		if match_log[i] == 'W':
			match_log = match_log[i:]
			head_length = i
			break
		if i == len(match_log) - 1:
			is_full_loses = True
			return (match_log, head_tail_length, is_full_loses)
	for j in range(len(match_log) - 1, -1, -1):
		if match_log[j] == 'W':
			tail_length = len(match_log) - j - 1
			match_log = match_log[:j + 1]
			break
	head_tail_length = head_length + tail_length
	return (match_log, head_tail_length, is_full_loses)

def find_optimal_cheat_points(head_tail_length, lose_sections_length, cheat_times):
	cheat_points = 0
	lose_sections_length = sorted(lose_sections_length)
	for lose_section_length in lose_sections_length:
		if cheat_times < lose_section_length:
			cheat_points += cheat_times * 2
			cheat_times = 0
			return cheat_points
		cheat_points += (lose_section_length - 1) * 2 + 3
		cheat_times -= lose_section_length
	if cheat_times > 0:
		cheat_points += min(cheat_times, head_tail_length) * 2
	return cheat_points

def catch_all_lose_exception(match_log, cheat_times):
	if cheat_times == 0:
		return 0
	return (min(len(match_log), cheat_times) - 1) * 2 + 1
test_amount = int(input())
for i in range(test_amount):
	(rounds, cheat_times) = tuple(map(int, input().split()))
	match_log = input()
	head_tail_length = 0
	(match_log, head_tail_length, is_full_loses) = remove_head_tail_losing_streak(match_log)
	if is_full_loses:
		print(catch_all_lose_exception(match_log, cheat_times))
	else:
		(lose_sections_length, original_points) = find_consecutive_lose_rounds(match_log)
		print(find_optimal_cheat_points(head_tail_length, lose_sections_length, cheat_times) + original_points)


from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
	(n, k) = map(int, stdin.readline().split())
	s = list(stdin.readline()[:-1])
	end = 0
	if 'W' not in s:
		print(max(0, 2 * k - 1))
		continue
	while s[-1] == 'L':
		end += 1
		del s[-1]
	s.reverse()
	while s[-1] == 'L':
		end += 1
		del s[-1]
	q = []
	now = []
	for i in range(len(s)):
		if s[i] == 'L':
			now.append(i)
		else:
			for j in now:
				q.append((len(now), j))
			now = []
	q.sort()
	for (num, ind) in q:
		if k <= 0:
			break
		s[ind] = 'W'
		k -= 1
	ans = min(end, k) * 2
	for i in range(len(s)):
		if s[i] == 'W':
			if i != 0 and s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	print(ans)


for _ in range(int(input())):
	(n, k) = [*map(int, input().split())]
	s = input()
	c = s.count('W')
	z = [0] * (c + 1)
	x = 0
	kk = k
	ans = 0
	if c == 0 and k > 0:
		ans -= 1
	for i in range(n):
		if i == 0:
			if s[i] == 'W':
				ans += 1
		if i != 0:
			if s[i] == 'W':
				if s[i - 1] == 'W':
					ans += 2
				else:
					ans += 1
		if s[i] == 'W':
			x += 1
		if s[i] == 'L':
			z[x] += 1
	a = z[0] + z[-1]
	z = z[1:c]
	z.sort()
	for i in z:
		if i == 0:
			continue
		elif k - i >= 0:
			ans += 1
			k -= i
		else:
			k = 0
			break
	if k > 0:
		if k >= a:
			k -= a
			ans += (kk - k) * 2
		else:
			ans += kk * 2
	else:
		ans += kk * 2
	print(ans)


import math
import os
import random
import re
import sys

def maxpts(str1, k):
	w = 0
	losses = []
	ans = 0
	W = False
	cur = 0
	for c in str1:
		if c == 'W':
			if cur:
				losses.append(cur)
				cur = 0
			w += 1
			ans += 1
			if W:
				ans += 1
			W = True
		else:
			W = False
			if w:
				cur += 1
	if w == 0:
		print(max(2 * k - 1, 0))
		return
	n = len(str1)
	if k >= n - w:
		print(n * 2 - 1)
		return
	ans += 2 * k
	losses.sort()
	for l1 in losses:
		if k >= l1:
			ans += 1
			k = k - l1
		else:
			break
	print(ans)
n = int(input())
for i in range(n):
	(n1, k) = map(int, input().rstrip().split())
	str1 = input()
	maxpts(str1, k)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	s1 = list(s)
	l = [len(i) for i in s.split('W')]
	w = 0
	if sum(l) <= k:
		print(2 * n - 1)
	else:
		prev = s[0]
		if prev == 'W':
			w += 1
		for i in s[1:]:
			if prev == i and i == 'W':
				w += 2
			elif i == 'W':
				w += 1
			prev = i
		m = sorted(l[1:-1], reverse=True)
		cm = len(m)
		while k != 0 and cm != 0:
			t = m[cm - 1]
			if t != 0:
				if k >= t:
					w += t * 2 + 1
					k -= t
				else:
					w += k * 2
					k = 0
			cm -= 1
		if len(l) == 1:
			g = l[0]
			if k != 0:
				w += k * 2 - 1
		elif len(l) == 2:
			g = l[0] + l[-1]
			if k != 0:
				if g == n:
					w += k * 2 - 1
				else:
					w += k * 2
		else:
			g = l[0] + l[-1]
			if k != 0:
				w += k * 2
		print(w)


import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None] * T
for qu in range(T):
	(N, K) = map(int, readline().split())
	S = [1 if s == 'W' else 0 for s in readline().strip()]
	if all((s == 0 for s in S)):
		Ans[qu] = max(0, 2 * K - 1)
		continue
	ans = 0
	ctr = 0
	st = []
	L = []
	res = 0
	hh = False
	for i in range(N):
		s = S[i]
		if s == 1:
			if i == 0 or S[i - 1] == 0:
				ans += 1
			else:
				ans += 2
			if ctr:
				st.append(ctr)
				ctr = 0
			hh = True
		elif hh:
			ctr += 1
		else:
			res += 1
	res += ctr
	st.sort()
	J = []
	for s in st:
		J.extend([2] * (s - 1) + [3])
	J.extend([2] * res)
	Ans[qu] = ans + sum(J[:min(len(J), K)])
print('\n'.join(map(str, Ans)))


t = int(input())
for x in range(t):
	(n, k) = input().split(' ')
	n = int(n)
	k = int(k)
	s = input()
	count_ = s.count('W')
	calculate = 0
	prev = 0
	li = []
	pre = -1
	for x in range(n):
		if s[x] == 'W':
			if pre == -1:
				pre = x
				calculate = 1
			else:
				li.append(x - pre - 1)
				if x - pre == 1:
					calculate += 2
				else:
					calculate += 1
				pre = x
	li.sort()
	for x in li:
		if x != 0:
			if k >= x:
				calculate += 2 * x + 1
				k = k - x
				count_ += x
			elif k < x:
				calculate += 2 * k
				count_ += k
				k = 0
				break
	if calculate == 0 and k > 0:
		calculate = -1
	if k != 0:
		if n - count_ >= k:
			calculate += 2 * k
			count_ += k
		elif n - count_ < k:
			calculate += 2 * (n - count_)
			count_ += n - count_
	print(calculate)


import sys
import math
from collections import defaultdict, deque
input = sys.stdin.readline

def inar():
	return [int(el) for el in input().split()]

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = inar()
		arr = list(input().strip())
		ans = 0
		ind = []
		for i in range(n):
			if arr[i] == 'W':
				ind.append(i)
		tup = []
		for i in range(1, len(ind)):
			el1 = ind[i - 1]
			el2 = ind[i]
			t = el2 - el1 - 1
			tup.append([t, el1, el2])
		tup.sort()
		for i in range(len(tup)):
			start = tup[i][1]
			end = tup[i][2]
			for j in range(start + 1, end):
				if k == 0:
					break
				if arr[j] == 'L':
					k -= 1
					arr[j] = 'W'
			if k == 0:
				break
		if k > 0:
			if len(ind) == 0:
				for i in range(n):
					if k == 0:
						break
					if arr[i] == 'L':
						k -= 1
						arr[i] = 'W'
			else:
				for i in range(ind[0] - 1, -1, -1):
					if k == 0:
						break
					if arr[i] == 'L':
						k -= 1
						arr[i] = 'W'
				for i in range(ind[-1] + 1, n):
					if k == 0:
						break
					if arr[i] == 'L':
						k -= 1
						arr[i] = 'W'
		temp = 0
		for i in range(n):
			if arr[i] == 'W':
				ans += temp + 1
				if temp == 0:
					temp = 1
			else:
				temp = 0
		print(ans)
main()


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

def RLE(s):
	cc = []
	ww = []
	pc = s[0]
	w = 0
	for c in s:
		if c == pc:
			w += 1
		else:
			cc.append(pc)
			ww.append(w)
			w = 1
			pc = c
	cc.append(pc)
	ww.append(w)
	return (cc, ww)
for _ in range(II()):
	(n, k) = MI()
	s = 'L' + SI() + 'L'
	(cc, aa) = RLE(s)
	if cc.count('W') < 2:
		a = s.count('W')
		print(max(0, min(k + a, n) * 2 - 1))
		continue
	ans = 0
	bb = []
	for (i, a) in enumerate(aa[1:-1]):
		if i & 1:
			bb.append(a)
		else:
			ans += 2 * a - 1
	bb.sort()
	for b in bb:
		if b > k:
			break
		ans += 2 * b + 1
		k -= b
	ans += 2 * k
	ans = min(ans, n * 2 - 1)
	print(ans)


import sys

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

def getMax(n):
	if n <= 1:
		return n
	else:
		return n * 2 - 1

def getPresentScore(len_arr):
	countZero = 0
	for l in len_arr:
		if l == 0:
			countZero += 1
	return len(len_arr) - 1 + countZero
t = int(input())
for i in range(t):
	[n, k] = list(map(int, input().split()))
	str_inp = input()
	str_inp = 'a' + str_inp + 'a'
	len_arr = list(map(lambda x: len(x), str_inp.split('W')))
	w_count = len(len_arr) - 1
	l_count = n - w_count
	presentScore = getPresentScore(len_arr)
	if l_count <= k:
		print(getMax(n))
		continue
	elif w_count == 0:
		print(getMax(k))
	elif w_count == 1:
		print(presentScore + k * 2)
	else:
		poss_seg = list(len_arr[1:-1])
		bonus = 0
		poss_seg.sort()
		k_copy = k
		for seg in poss_seg:
			if seg == 0:
				continue
			elif seg <= k:
				bonus += 1
				k -= seg
			else:
				break
		print(presentScore + k_copy * 2 + bonus)


import os, sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		s = input().strip()
		if n == 1:
			if s[0] == 'W' or k:
				print(1)
			else:
				print(0)
			continue
		curr = int(s[0] == 'W')
		for i in range(1, n):
			if s[i] == 'W':
				curr += 1 + int(s[i - 1] == 'W')
		(fl, cou) = (0, 0)
		loss = []
		le = 0
		for i in range(n):
			if s[i] == 'W':
				fl = 1
				if cou:
					loss.append(cou)
					cou = 0
			elif fl:
				cou += 1
			else:
				le += 1
		if le == n:
			print(max(0, 2 * min(n, k) - 1))
			continue
		re = cou
		loss.sort()
		i = 0
		while i != len(loss):
			if k >= loss[i]:
				k -= loss[i]
				curr += 2 * loss[i] + 1
			elif k < loss[i]:
				curr += 2 * k
				k = 0
				break
			i += 1
		curr += min(re + le, k) * 2
		print(curr)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for i in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	wins = s.count('W') + k
	if wins >= n:
		print(2 * n - 1)
	else:
		streaks = int(s[0] == 'W') + s.count('LW') or int(wins > 0)
		gaps = s.strip('L').replace('W', ' ').strip().split()
		for g in sorted(map(len, gaps)):
			if g > k:
				break
			k -= g
			streaks -= 1
		print(wins * 2 - streaks)


from sys import stdin
t = int(stdin.readline())
for i in range(t):
	(n, k) = tuple((int(x) for x in stdin.readline().split()))
	line = 'L' * (k + 1) + stdin.readline()[:-1] + 'L' * (k + 1)
	score = 0
	flag = False
	for char in line:
		if char == 'W':
			if flag:
				score += 2
			else:
				score += 1
				flag = True
		else:
			flag = False
	seq = sorted((len(x) for x in line.split('W')))
	if len(seq) == 1:
		if k == 0:
			print(0)
		else:
			print(2 * k - 1)
		continue
	for item in seq:
		if item == 0:
			continue
		if k - item >= 0:
			k -= item
			score += 2 * (item - 1) + 3
		elif k > 0:
			score += 2 * k
			break
		else:
			break
	print(min(score, 2 * n - 1))


for __ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	ar = list(input())
	kek = []
	ans = 0
	if 'W' in ar:
		i = ar.index('W')
		flag = 0
		cnt = 0
		while i < n:
			if ar[i] == 'L' and flag == 0:
				flag = 1
				cnt = 1
			elif ar[i] == 'L':
				cnt += 1
			elif ar[i] == 'W' and flag == 1:
				kek.append(cnt)
				flag = 0
			i += 1
	else:
		ans -= 1
	kek.sort()
	bebe = m
	j = 0
	while bebe > 0 and j < len(kek):
		if bebe - kek[j] >= 0:
			ans += kek[j] * 2 + 1
		else:
			break
		bebe -= kek[j]
		j += 1
	ans += 2 * (bebe - max(0, m - ar.count('L')))
	for i in range(n):
		if i == 0:
			if ar[i] == 'W':
				ans += 1
		elif ar[i] == ar[i - 1] == 'W':
			ans += 2
		elif ar[i] == 'W':
			ans += 1
	print(max(ans, 0))


import heapq

def solve(st, n, k):
	prev = 'L'
	(c, bug) = (0, k)
	li = []
	score = 0
	count_l = st.count('L')
	if count_l == n:
		return max(2 * min(k, n) - 1, 0)
	for it in st:
		if it == prev:
			if it == 'W':
				score += 2
			c += 1
		else:
			if it == 'W':
				score += 1
			li.append(c)
			c = 1
		prev = it
	if c:
		li.append(c)
	hl = []
	heapq.heapify(hl)
	ln = len(li)
	i = 2
	while i + 1 < ln:
		it = li[i]
		heapq.heappush(hl, it)
		i += 2
	while hl:
		tp = heapq.heappop(hl)
		if tp <= bug:
			bug -= tp
			count_l -= tp
			score += 2 * tp + 1
	cngo = min(bug, count_l)
	score += 2 * cngo
	return score
for case in range(int(input())):
	(n, k) = map(int, input().split())
	st = input()
	ans = solve(st, n, k)
	print(ans)


t = input
for i in range(int(t())):
	(n, k) = map(int, t().split())
	a = sorted(map(len, t().strip('L').split('W')))
	m = len(a) + k
	while a and k >= a[0]:
		k -= a.pop(0)
	print((2 * min(n, m - 1) - len(a) or 1) - 1)


import sys
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = sys.stdin.readline().strip()
	s = list(s)
	q = 0
	p = []
	for j in range(n):
		if s[j] == 'W':
			if q > 0:
				p.append([q, j - 1])
			q = 0
		else:
			q = q + 1
	if q > 0:
		if p == [] and s[0] != 'W':
			p.append([q, n - 1])
		else:
			p.append([q, n - q])
		q = 0
	if p:
		e1 = []
		e2 = []
		if s[0] == 'L':
			e1.append(p[0])
			del p[0]
		if p:
			if s[-1] == 'L':
				e2.append(p[-1])
				del p[-1]
		p.sort()
		p = p + e1
		j = 0
		l = len(p)
		while k > 0 and j < l:
			v = p[j][1]
			while v >= 0 and s[v] == 'L' and (k > 0):
				s[v] = 'W'
				v = v - 1
				k = k - 1
			j = j + 1
		if k > 0 and e2:
			j = e2[0][1]
			while k > 0 and j < n:
				s[j] = 'W'
				k = k - 1
				j = j + 1
	w = 0
	for j in range(1, n):
		if s[j] == s[j - 1] and s[j] == 'W':
			w = w + 2
		elif s[j] == 'W':
			w = w + 1
	if s[0] == 'W':
		w = w + 1
	print(w)


naborov = int(input())
ks = []
sets = []
for _ in range(naborov):
	ks.append(int(input().split()[1]))
	sets.append(input())
import collections as clc

def count(ss):
	col = clc.Counter()
	if s[0] == 'W':
		res = 1
		prev = 0
		first = 0
	else:
		res = 0
		prev = None
	for i in range(1, len(ss)):
		if ss[i] == 'W':
			if ss[i - 1] == 'W':
				res += 2
			else:
				res += 1
			if prev == None:
				first = i
			elif prev < i - 1:
				col[i - 1 - prev] += 1
			prev = i
	last = i - prev
	return (res, col, first, last)

def treat(ss, k):
	col = clc.Counter(ss)
	if col['L'] <= k:
		return len(ss) * 2 - 1
	elif col['W'] == 0:
		return max(0, 2 * k - 1)
	(res, col, first, last) = count(s)
	for d in sorted(col.keys()):
		if d * col[d] <= k:
			k -= d * col[d]
			res += (d * 2 + 1) * col[d]
		else:
			(t, k) = divmod(k, d)
			res += (d * 2 + 1) * t
			break
	res += k * 2
	return res
for (s, k) in zip(sets, ks):
	print(treat(s, k))


def solve():
	(n, k) = map(int, input().split())
	s = list(input())
	i = 0
	cnt = 0
	la = []
	for i in range(n):
		if s[i] == 'W':
			la.append(i)
		else:
			cnt += 1
	if la == []:
		for i in range(n):
			if k == 0:
				break
			s[i] = 'W'
			k -= 1
	elif k >= cnt:
		s = list('W' * n)
	else:
		ha = []
		for j in range(len(la) - 1):
			ha.append((la[j + 1] - la[j], la[j], la[j + 1]))
		ha.sort()
		for i in range(len(ha)):
			(a, b, c) = ha[i]
			for j in range(b + 1, c):
				if k == 0:
					break
				s[j] = 'W'
				k -= 1
		(a, b) = (la[0], la[-1])
		for i in range(b + 1, n):
			if k == 0:
				break
			s[i] = 'W'
			k -= 1
		for i in range(a - 1, -1, -1):
			if k == 0:
				break
			s[i] = 'W'
			k -= 1
	ans = 0
	for i in range(n):
		if i - 1 >= 0 and s[i] == 'W' and (s[i - 1] == 'W'):
			ans += 2
		elif s[i] == 'W':
			ans += 1
	print(ans)
t = int(input())
for _ in range(t):
	solve()


t = int(input())
for _ in range(t):
	l = list(map(int, input().split()))
	(n, k) = (l[0], l[1])
	s = str(input())
	score = 0
	key = 1
	for i in range(n):
		if s[i] == 'L':
			key = 1
		else:
			score += key
			key = 2
	l = []
	(count, count2) = (0, 0)
	ind = 0
	for i in range(n):
		if s[i] == 'L' and ind == 0:
			count2 += 1
		elif s[i] == 'L' and ind == 1:
			count += 1
		elif s[i] == 'W' and ind == 0:
			ind = 1
		elif count > 0:
			l.append(count)
			count = 0
	count3 = 0
	if count > 0:
		count3 = count
	countf = count2 + count3
	l.sort()
	p = len(l)
	x = k
	inc = 0
	for i in range(p):
		if x >= l[i]:
			x = x - l[i]
			inc += 2 * l[i] + 1
		else:
			inc += 2 * x
			x = 0
		if x == 0:
			break
	if x > 0:
		inc += 2 * min(x, count3)
		x -= min(x, count3)
	if x > 0:
		if 'W' in s:
			inc += 2 * min(x, count2)
			x -= min(x, count2)
		else:
			inc += 2 * min(x, count2) - 1
			x -= min(x, count2)
	print(score + inc)


import sys
rd = sys.stdin.readline
t = int(rd())
for _ in range(t):
	(n, k) = map(int, rd().split())
	s = rd()
	if n == 1:
		if s[0] == 'L' and k == 0:
			print(0)
		else:
			print(1)
		continue
	gap = [0] * (n - 1)
	renpai = 0
	score = 0
	(startrenpai, lastrenpai) = (0, 0)
	for i in range(n):
		if s[i] == 'L':
			renpai += 1
			if i == n - 1:
				lastrenpai = renpai
		else:
			if i >= 1 and s[i - 1] == 'W':
				score += 2
			else:
				score += 1
			if renpai == i:
				startrenpai = renpai
			else:
				gap[renpai] += 1
			renpai = 0
	if n == lastrenpai:
		print(max(0, 2 * min(k, n) - 1))
		continue
	now = 1
	while True:
		if now == n - 1:
			score += 2 * min(k, startrenpai + lastrenpai)
			break
		if gap[now] > 0:
			if k >= now:
				score += 2 * now + 1
				k -= now
			else:
				score += 2 * k
				break
			gap[now] -= 1
		else:
			now += 1
	print(score)


from sys import stdin, stdout
input = stdin.readline
print = lambda x: stdout.write(str(x) + '\n')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input().strip()
	Ws = 0
	prev = 0
	for i in s:
		if i == 'W':
			if prev:
				Ws += 2
			else:
				Ws += 1
				prev = 1
		elif prev:
			prev = 0
	if not Ws:
		if not k:
			print(0)
			continue
		ans = min(k, n) * 2 - 1
		print(ans)
		continue
	start = 0
	mid = []
	end = 0
	w = 0
	curr = 0
	for g in s:
		if g == 'L':
			curr += 1
		else:
			if w:
				if curr:
					mid.append(curr)
			else:
				start += curr
				w = 1
			curr = 0
	end = curr
	mid.sort()
	i = 0
	c = 0
	score = 0
	while c < k and i < len(mid):
		if c + mid[i] <= k:
			score += mid[i] * 2 + 1
		else:
			score += (k - c) * 2
		c += mid[i]
		i += 1
	if k - c > 0:
		if c + start <= k:
			score += start * 2
		else:
			score += (k - c) * 2
		c += start
		if k - c > 0:
			if c + end <= k:
				score += end * 2
			else:
				score += (k - c) * 2
			c += end
	print(score + Ws)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n, k) = I()
	s = list(input().strip())
	if s.count('W') == 0:
		print(max(0, 1 + 2 * (k - 1)))
		continue
	i = 0
	le = []
	for i in range(n):
		if s[i] == 'W':
			le.append(i)
	ne = []
	for i in range(len(le) - 1):
		ne.append([le[i], le[i + 1], le[i + 1] - le[i] - 1])
	ne.sort(key=lambda x: x[2])
	for i in ne:
		now = i[0] + 1
		while now < i[1] and k:
			s[now] = 'W'
			now += 1
			k -= 1
		if not k:
			break
	temp = []
	if s[0] != 'W':
		temp.append([-1, le[0], le[0] - -1 - 1])
	if s[-1] != 'W':
		temp.append([le[-1], n, n - le[-1] - 1])
	temp.sort(key=lambda x: x[2])
	for i in temp:
		if i[0] == -1:
			now = i[1] - 1
			while now >= 0 and k:
				k -= 1
				s[now] = 'W'
				now -= 1
		else:
			now = i[0] + 1
			while now < i[1] and k:
				s[now] = 'W'
				k -= 1
				now += 1
		if not k:
			break
	ans = 1 if s[0] == 'W' else 0
	for i in range(1, n):
		if s[i - 1] == 'W' and s[i] == 'W':
			ans += 2
		elif s[i] == 'W':
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(input())
	m = a.count('L')
	d = a.count('W')
	if m <= k:
		print(2 * (n - 1) + 1)
		continue
	if d == 0:
		print(max(2 * (k - 1) + 1, 0))
	else:
		for i in range(n):
			if a[i] == 'W':
				b = i
				break
		a.reverse()
		for i in range(n):
			if a[i] == 'W':
				c = i
				break
		j = n - c
		x = c
		c = j
		a.reverse()
		l = []
		s = 0
		for i in range(b, c):
			if a[i] == 'L':
				s = s + 1
			elif s == 0:
				pass
			else:
				l.append(s)
				s = 0
		l.sort()
		ans = 0
		for i in range(len(l)):
			if k >= l[i]:
				k = k - l[i]
				ans = ans + 2 * l[i] + 1
			else:
				ans = ans + 2 * k
				k = 0
				break
		if k == 0:
			pass
		else:
			z = min(k, b + x)
			ans = ans + 2 * z
		if a[0] == 'W':
			ans = ans + 1
		for i in range(1, n):
			if a[i] == 'W' and a[i - 1] == 'W':
				ans = ans + 2
			elif a[i] == 'W' and a[i - 1] == 'L':
				ans = ans + 1
		print(ans)


import sys, os
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

def solve_(lst, k):
	length = len(lst)
	lst = lst
	if sum(lst) + k >= length:
		return 2 * length - 1
	if sum(lst) == 0:
		return max(0, k * 2 - 1)
	lst = ''.join((str(x) for x in lst))
	lst = lst.strip('0')
	lst = [int(x) for x in lst]
	console(lst)
	spaces = []
	prev = 0
	curspace = 0
	for a in lst:
		if prev == 0 and a == 1:
			spaces.append(curspace)
			curspace = 0
		if a == 0:
			curspace += 1
		prev = a
	spaces = spaces[1:]
	spaces = sorted(spaces)
	console('spaces', spaces, k)
	res = 2 * sum(lst) - len(spaces) - 1
	console('initial', res)
	for a in spaces:
		if a <= k:
			k -= a
			res += a * 2 + 1
	console('filled', res)
	console('remainder', k)
	res += k * 2
	return res

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	pass
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def console(*args):
		pass

def solve(*args):
	return solve_(*args)
if True:
	inp = iter(sys.stdin.buffer.readlines())
	input = lambda : next(inp)
else:
	input = sys.stdin.buffer.readline
cout = []
for case_num in range(int(input())):
	(_, k) = list(map(int, input().split()))
	lst = input().strip()
	lst = [0 if x == 76 else 1 for x in lst]
	res = solve(lst, k)
	cout.append(str(res))
print('\n'.join(cout))


import re

def cal_base_score(input_string):
	W_list = re.findall('W+', input_string)
	score = sum([2 * (len(w) - 1) + 1 for w in W_list])
	return score
total_samples = int(input())
for i in range(total_samples):
	(length, modify) = map(int, input().split())
	string = input()
	w_count = string.count('W')
	l_count = length - w_count
	base_score = cal_base_score(string)
	if 'W' not in string:
		print(max(0, 2 * modify - 1))
	else:
		start = string.find('W')
		end = string.rfind('W')
		if start == end:
			s = 'W'
		else:
			s = string[start:end]
		stack = sorted(re.findall('L+', s), reverse=True)
		while modify > 0 and len(stack) > 0:
			seg = stack.pop()
			modify -= 1
			if seg == 'L':
				base_score += 3
			else:
				base_score += 2
				stack.append(seg.replace('L', '', 1))
		first_l_seg = string[:start]
		last_l_seg = string[end:]
		if modify > 0:
			for _ in range(len(first_l_seg) + len(last_l_seg)):
				base_score += 2
				modify -= 1
				if modify <= 0:
					break
		base_score = min(base_score, 2 * length - 1)
		print(base_score)


for t in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	wd = input()
	sc = 0
	if wd[0] == 'W':
		sc += 1
	ls = []
	l_cnt = 0
	for i in range(1, n):
		if wd[i] == 'W':
			if wd[i - 1] == 'W':
				sc += 2
			else:
				sc += 1
	for i in range(n):
		if wd[i] == 'W':
			if len(ls) == 0 or ls[-1] != 0:
				ls.append(0)
		else:
			l_cnt += 1
			if ls:
				ls[-1] += 1
	if l_cnt <= k:
		print(2 * n - 1)
		continue
	if ls:
		ls.pop()
	else:
		print(max(0, 2 * k - 1))
		continue
	sm = 0
	ls.sort()
	ext = 0
	for ll in ls:
		if sm + ll <= k:
			sm += ll
			ext += 1
		else:
			break
	assert sc + 2 * k + ext <= 2 * n - 1
	print(sc + 2 * k + ext)


for _ in range(int(input())):
	(n, k) = map(int, input().split(' '))
	s = input()
	if s[0] == 'W':
		score = 1
	else:
		score = 0
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				score = score + 2
			else:
				score = score + 1
	start = []
	i = 0
	while i < n:
		if s[i] == 'L':
			j = i + 1
			a = [i]
			while j < n and s[j] == 'L':
				j = j + 1
			i = j
			a.append(i)
			start.append(a)
		else:
			i = i + 1
	add_score = 0
	f = 0
	p = 0
	if len(start) > 0:
		if start[0][0] == 0:
			p = start[0][1] - start[0][0]
			s1 = start[1:len(start)]
			f = 1
		else:
			s1 = start
		g = 0
		p1 = 0
		if len(s1) != 0:
			if s1[-1][1] == n:
				p1 = s1[-1][1] - s1[-1][0]
				s1 = s1[0:len(s1) - 1]
				g = 1
		for item in s1:
			item.append(item[1] - item[0])
		s1.sort(key=lambda x: x[2])
		t = len(s1)
		for item in s1[0:t]:
			if k >= item[2]:
				k = k - item[2]
				add_score = add_score + 2 * item[2] + 1
			else:
				add_score = add_score + 2 * k
				k = 0
			if k == 0:
				break
		if f == 1 or (g == 1 and k != 0):
			add_score = add_score + 2 * min(p + p1, k)
		if n == 1:
			if k >= n:
				print(1)
			elif s == 'W':
				print(1)
			else:
				print(0)
		elif len(set(s)) == 1 and s[0] == 'L':
			print(max(0, score + add_score - 1))
		else:
			print(score + add_score)
	else:
		print(score)


import collections

def readis():
	return map(int, input().strip().split())

def printlist(xs):
	print(' '.join(map(str, xs)))
T = int(input())
while T:
	T -= 1
	(n, k) = readis()
	s = input()
	cs = list(s)
	loss_start = -1
	loss_conts = []
	l_beg = 0
	l_end = 0
	score = 0
	for (i, c) in enumerate(s):
		if c == 'W':
			score += 1 + int(i > 0 and s[i - 1] == 'W')
	if set(s) == {'L'}:
		n_reverts = min(len(s), k)
		inc = 2 * n_reverts - 1 if n_reverts else 0
		print(score + inc)
		continue
	if set(s) == {'W'}:
		print(score)
		continue
	for (i, c) in enumerate(s):
		if loss_start > -1:
			if c == 'W':
				if loss_start == 0:
					l_beg = i
				else:
					loss_conts.append(i - loss_start)
				loss_start = -1
		elif c == 'L':
			loss_start = i
	if loss_start > -1:
		l_end = n - loss_start
	max_score = score
	for cont in sorted(loss_conts):
		if k > 0:
			n_cheats = min(k, cont)
			k -= n_cheats
			max_score += 2 * n_cheats + int(n_cheats == cont)
		else:
			break
	if k > 0 and l_end:
		n_cheats = min(k, l_end)
		k -= n_cheats
		max_score += 2 * n_cheats
	if k > 0 and l_beg:
		n_cheats = min(k, l_beg)
		k -= n_cheats
		max_score += 2 * n_cheats
	print(max_score)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(input())
	f = False
	loss = 0
	arr = []
	start = 0
	last = 0
	ans = 0
	if n == a.count('L') and k > 0:
		ans -= 1
	for i in range(n):
		if a[i] == 'W':
			f = True
		if f and i > 0:
			if a[i] == 'L' and a[i - 1] == 'L':
				loss += 1
			elif a[i] == 'L':
				loss = 1
			elif loss != 0:
				arr.append(loss)
				loss = 0
	if loss != 0:
		arr.append(loss)
	if a[-1] != 'W' and len(arr) > 0:
		last = arr.pop()
	for i in range(n):
		if a[i] == 'L':
			start += 1
		else:
			break
	arr.sort()
	if a[0] == 'W':
		ans += 1
	for i in range(1, n):
		if a[i] == a[i - 1] and a[i] == 'W':
			ans += 2
		elif a[i] == 'W':
			ans += 1
	for i in arr:
		if k - i >= 0:
			ans += i * 2
			ans += 1
			k -= i
		else:
			ans += k * 2
			k = 0
	(start, last) = (min(start, last), max(start, last))
	if k - start >= 0:
		k -= start
		ans += start * 2
	else:
		ans += k * 2
		k = 0
	if k - last >= 0:
		k -= last
		ans += last * 2
	else:
		ans += k * 2
		k = 0
	print(ans)


import math
T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	a = list(input())
	d = False
	gaps = []
	l = 0
	st = a[0] != 'W'
	for i in range(n):
		if a[i] == 'L':
			l += 1
		elif l != 0 and (not st):
			gaps.append(l)
			l = 0
		elif l != 0:
			st = 0
			l = 0
	k1 = k
	gaps.sort()
	lg = len(gaps)
	for i in range(lg):
		k -= gaps[i]
		if k >= 0:
			lg -= 1
		else:
			break
	ans = 2 * min(a.count('W') + k1, n)
	ans -= lg + 1
	print(max(ans, 0))


from sys import stdin, stdout
from math import ceil, floor, sqrt, log, log2, log10
from collections import Counter
input = stdin.readline

def solve():
	pass
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input().strip()
	curr = n + 100
	streaks = []
	out = 0
	wins = k
	for i in range(n - 1):
		if s[i] == 'W' and s[i + 1] == 'W':
			out += 1
	for c in s:
		if c == 'W':
			streaks.append(curr)
			curr = 0
			out += 1
			wins += 1
		else:
			curr += 1
	streaks.sort()
	out += 2 * k
	for v in streaks:
		if v > 0 and v <= k:
			k -= v
			out += 1
	print(min([2 * n - 1, out, max(0, 2 * wins - 1)]))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	w = s.count('W')
	if s.count('L') <= k:
		ans = 2 * n - 1
		print(ans)
	elif k == 0 and w == 0:
		print(0)
	else:
		i = 0
		c1 = s.find('W')
		c2 = s.rfind('W')
		if c1 == -1:
			ans = 2 * k - 1
		else:
			l = []
			s = s[c1 + 1:c2]
			i = 0
			c = 0
			while i < len(s):
				if s[i] == 'L':
					c = 1
					j = i + 1
					while j < len(s) and s[j] == 'L':
						c += 1
						j += 1
					l.append(c)
					i = j
				else:
					i += 1
			l.sort()
			i = 0
			streak = len(l) + 1
			k0 = k
			while i < len(l) and k > 0:
				if l[i] <= k:
					k -= l[i]
					streak -= 1
				i += 1
			if streak == 0:
				ans = 2 * (w + k0) - 1
			else:
				ans = 2 * (w + k0) - streak
		print(ans)


t = int(input())

def func(arr, n):
	start = None
	end = None
	for i in range(n):
		if arr[i] == 'W':
			start = i
			break
	for i in reversed(range(n)):
		if arr[i] == 'W':
			end = i
			break
	return (start, end)
while t > 0:
	t -= 1
	(n, k) = list(map(int, input().split()))
	arr = input()
	(start, end) = func(arr, n)
	dict = {}
	streak = 0
	point = 0
	if start != None and end != None:
		for i in range(start, end + 1):
			if arr[i] == 'L':
				streak += 1
				if arr[i + 1] != 'L':
					if streak in dict:
						dict[streak] += 1
					else:
						dict[streak] = 1
					streak = 0
			elif i != start:
				if arr[i - 1] == 'W':
					point += 2
				else:
					point += 1
			else:
				point += 1
	for score in sorted(dict):
		if k > 0:
			if k >= score * dict[score]:
				k -= score * dict[score]
				point += score * dict[score] * 2 + dict[score]
			else:
				point += k * 2
				point += k // score
				k = 0
		else:
			break
	if start == None:
		left = n
	else:
		left = start + (n - end - 1)
	if k > 0:
		if start != None:
			if k >= left:
				point += left * 2
				k -= left
			else:
				point += k * 2
				k -= k
		elif k >= left:
			point += left * 2 - 1
			k -= left
		else:
			point += k * 2 - 1
			k -= k
	print(point)


from collections import defaultdict
mod = 10 ** 9 + 7
INF = float('inf')

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

def inverse(N, mod):
	return pow(N, mod - 2, mod)

def main():
	T = int(input())
	for _ in range(T):
		(N, K) = getlist()
		s = list(input())
		K2 = K
		num = s.count('W')
		if num == 0:
			ans = 2 * min(N, K) - 1
			print(max(ans, 0))
		else:
			Lis = []
			cnt = 0
			for i in s:
				if i == 'L':
					cnt += 1
				elif cnt != 0:
					Lis.append(cnt)
					cnt = 0
			if cnt != 0:
				Lis.append(cnt)
			Lis2 = []
			M = len(Lis)
			seg = M - 1
			cnt2 = 0
			(S, G) = (0, M)
			if s[0] == 'W':
				seg += 1
			else:
				S += 1
			if s[-1] == 'W':
				seg += 1
			else:
				G -= 1
			for i in range(S, G):
				Lis2.append(Lis[i])
			Lis2.sort()
			M2 = len(Lis2)
			for i in range(M2):
				if K >= Lis2[i]:
					seg -= 1
					K -= Lis2[i]
				else:
					break
			ans = 2 * min(N, num + K2) - seg
			print(ans)
main()


for t in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	if k >= n:
		print(n * 2 - 1)
		continue
	l = 0
	inter = []
	count = 0
	out = 0
	for i in s:
		if i == 'L':
			l += 1
			count += 1
		else:
			if count != 0:
				inter.append(count)
				out += 1
			else:
				out += 2
			count = 0
	if s[0] == 'W':
		out -= 1
	elif inter:
		inter.pop(0)
	if l <= k:
		print(n * 2 - 1)
	elif l == n and k != 0:
		print(k * 2 - 1)
	else:
		r = n - l
		inter.sort()
		for i in inter:
			if k >= i:
				out += i * 2 + 1
				k -= i
			else:
				out += k * 2
				k = 0
				break
		out += k * 2
		print(out)


def chess(string, n):
	temp = sorted(map(len, string.strip('L').split('W')))
	m = len(temp) + n
	while temp and temp[0] <= n:
		n -= temp.pop(0)
	return (2 * min(len(string), m - 1) - len(temp) or 1) - 1
t = int(input())
for i in range(t):
	(a, b) = map(int, input().strip().split())
	print(chess(input(), b))


import sys
input = sys.stdin.readline

def solution(n, k, s):
	seq_lengths_L = []
	count_L_seq = 0
	first = 0
	last = 0
	score = 0
	for pos in range(n):
		if s[pos] == 'W':
			if pos > 0 and s[pos - 1] == 'W':
				score += 2
			else:
				score += 1
	if k == 0:
		print(score)
		return
	for char in s:
		if char == 'L':
			count_L_seq += 1
		else:
			seq_lengths_L.append(count_L_seq)
			count_L_seq = 0
	seq_lengths_L.append(count_L_seq)
	if len(seq_lengths_L) == 1:
		print(min(2 * n - 1, 2 * k - 1))
		return
	first = seq_lengths_L[0]
	last = seq_lengths_L[-1]
	seq_lengths_L = seq_lengths_L[1:-1]
	seq_lengths_L.sort()
	for diff in seq_lengths_L:
		if diff > 0:
			if diff <= k:
				score += 2 * diff + 1
				k -= diff
			else:
				score += 2 * k
				print(score)
				return
	if first <= k:
		score += 2 * first
		k -= first
	else:
		score += 2 * k
		print(score)
		return
	score += 2 * min(last, k)
	print(score)
	return
T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	s = input().strip()
	solution(n, k, s)


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	s = str(input())
	ind = []
	arr = []
	p = 0
	for i in range(n):
		arr.append(s[i])
		if s[i] == 'W':
			ind.append(i + 1)
			p += 1
	if p == 0:
		if k == 0:
			print(0)
		else:
			print(1 + 2 * (k - 1))
	else:
		ans = 0
		i = 0
		q = -1
		while i < n:
			if arr[i] == 'W':
				ans += 1
				q = i
				break
			i += 1
		for i in range(q + 1, n):
			if arr[i] == 'W':
				if arr[i - 1] == 'W':
					ans += 2
				else:
					ans += 1
		if k == 0:
			print(ans)
		else:
			diff = []
			f = 0
			for i in range(p - 1):
				if ind[i + 1] - ind[i] - 1 > 0:
					diff.append(ind[i + 1] - ind[i] - 1)
					f += 1
			diff.sort()
			i = 0
			while k > 0 and i < f:
				if diff[i] == 1:
					diff[i] -= 1
					i += 1
					k -= 1
					ans += 3
				else:
					diff[i] -= 1
					k -= 1
					ans += 2
			if k > 0:
				c = ind[0] - 1 + (n - ind[-1])
				ans += 2 * min(c, k)
			print(ans)


ts = int(input())
for t in range(ts):
	(n, k) = [int(i) for i in input().split(' ')]
	l = input()
	c = 0
	wc = 0
	d = {}
	be = 0
	head = 0
	tail = n
	for i in l:
		if i == 'L':
			head += 1
			be += 1
		else:
			break
	for i in range(n - 1, -1, -1):
		if l[i] == 'L':
			tail -= 1
			be += 1
		else:
			break
	for i in range(head, tail):
		if l[i] == 'W':
			if i == 0:
				wc += 1
			elif l[i - 1] == 'W':
				wc += 2
			else:
				wc += 1
			if c > 0:
				if c in d.keys():
					d[c] += 1
				else:
					d[c] = 1
				c = 0
		else:
			c += 1
	ks = sorted(list(d.keys()))
	ki = 0
	klen = len(ks)
	while k > 0 and ki < klen:
		ky = ks[ki]
		dval = d[ky]
		if k // ky >= dval:
			wc += (1 + 2 * ky) * dval
			k -= ky * dval
		else:
			wc += (1 + 2 * ky) * (k // ky) + 2 * (k % ky)
			k = 0
		ki += 1
	if k > 0:
		if tail == 0:
			wc += 2 * min(k, be) - 1
		else:
			wc += 2 * min(k, be)
	print(wc)


import sys
T = int(sys.stdin.readline())
for t in range(0, T):
	(n, k) = list(map(int, sys.stdin.readline().strip().split()))
	s = sys.stdin.readline().strip()
	ans = 0
	v = False
	k2 = k
	x = 0
	y = 0
	if s[0] == 'W':
		y = 1
		ans = 1
		v = True
	else:
		x = 1
	L = []
	for i in range(1, n):
		if s[i] == 'W':
			if x > 0:
				L.append(x)
			if v == True:
				ans = ans + 2
			else:
				ans = ans + 1
				v = True
			x = 0
			y = y + 1
		else:
			v = False
			x = x + 1
	L2 = []
	if x > 0:
		L2.append(x)
	if s[0] == 'L' and len(L) > 0:
		L2.append(L[0])
		L = L[1:]
	L.sort()
	L.reverse()
	while k > 0 and len(L) > 0:
		l = L.pop()
		if l <= k:
			k = k - l
			ans = ans + 2 * l + 1
		else:
			ans = ans + 2 * k
			k = 0
	if k > 0:
		ans = ans + min(sum(L2), k) * 2
	if y > 0:
		print(ans)
	else:
		print(max(0, 2 * k2 - 1))


import sys

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	(n, k) = mints()
	i = 0
	p = None
	pos = []
	a = list(minp())
	for i in range(n):
		if a[i] == 'W':
			if p is not None:
				pos.append((i - p - 1, p + 1))
			else:
				first = i
			p = i
	pos.sort()
	for (l, f) in pos:
		if k == 0:
			break
		for i in range(f, f + l):
			if k > 0:
				k -= 1
				a[i] = 'W'
			else:
				break
	if p is not None:
		for i in range(p - 1, -1, -1):
			if a[i] != 'W':
				if k > 0:
					a[i] = 'W'
					k -= 1
				else:
					break
	for i in range(n):
		if a[i] != 'W':
			if k > 0:
				a[i] = 'W'
				k -= 1
			else:
				break
	ans = 0
	cnt = 0
	for i in range(n):
		if a[i] == 'W':
			cnt = min(cnt + 1, 2)
			ans += cnt
		else:
			cnt = 0
	print(ans)
for i in range(mint()):
	solve()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = str(input())
	a = 0
	b = 0
	kek = []
	fl = 0
	su = 0
	rs = 0
	buf = 10000000000.0
	buf1 = 10000000000.0
	for i in range(len(s)):
		if s[i] == 'W':
			if a > 0:
				su += a
				if fl == 0:
					buf1 = a
				else:
					kek.append(a)
				a = 0
			fl = 1
			b += 1
		else:
			if b > 0:
				rs += 2 * (b - 1) + 1
				b = 0
			a += 1
	if a > 0:
		su += a
		if fl == 0:
			buf1 = a
		else:
			buf = a
		a = 0
	if b > 0:
		rs += 2 * (b - 1) + 1
		b = 0
	if su <= k or rs == n * 2 - 1:
		print(n * 2 - 1)
	else:
		kek.sort()
		k1 = k
		for el in kek:
			if k1 >= el:
				rs += el * 2 + 1
				k1 -= el
			else:
				rs += k1 * 2
				k1 = 0
		if k1 > 0 and buf < 10000000000.0:
			if k1 >= buf:
				k1 -= buf
				rs += buf * 2
			else:
				rs += k1 * 2
				k1 = 0
		if k1 > 0:
			if k1 >= buf1:
				k1 -= buf1
				rs += buf1 * 2 - (not fl)
			else:
				rs += k1 * 2 - (not fl)
				k1 = 0
		print(rs)


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

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

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = float('inf')
mod = 10 ** 9 + 7
for t in range(int(data())):
	(n, k) = mdata()
	s = data()
	l = []
	ind = -1
	ans = 0
	a = 0
	for i in range(n):
		if s[i] == 'W':
			l.append([i - ind - 1, ind + 1])
			ind = i
			ans += 1
			if i > 0 and s[i - 1] == 'W':
				ans += 1
	l.append([n - ind - 1, ind + 1])
	a = l.pop(0)
	b = [0, 0]
	if l:
		b = l.pop()
	l.sort(key=lambda x: x[0])
	l = l[::-1]
	for i in range(len(l) - 1, -1, -1):
		if l[i][0] > 0:
			if l[i][0] <= k:
				ans += 2 * l[i][0] + 1
				k -= l[i][0]
				if l[i][1] == 0:
					ans -= 1
				if l[i][1] + l[i][0] == n:
					ans -= 1
			else:
				break
		l.pop()
	l.append(a)
	l.append(b)
	for i in l:
		if i[0] > 0:
			if i[0] <= k:
				ans += 2 * i[0] + 1
				k -= i[0]
				if i[1] == 0:
					ans -= 1
				if i[1] + i[0] == n:
					ans -= 1
			elif k:
				ans += 2 * k
				if i[1] == 0 or s[i[1] - 1] != 'W':
					if i[1] + i[0] == n:
						ans -= 1
					elif s[i[1] + i[0]] != 'W':
						ans -= 1
				break
	out(ans)


from __future__ import division, print_function
import bisect
import math
import heapq
import itertools
import sys
from collections import deque
from atexit import register
from collections import Counter
from functools import reduce
if sys.version_info[0] < 3:
	from io import BytesIO as stream
else:
	from io import StringIO as stream
if sys.version_info[0] < 3:

	class dict(dict):

		def items(self):
			return dict.iteritems(self)

		def keys(self):
			return dict.iterkeys(self)

		def values(self):
			return dict.itervalues(self)
	input = raw_input
	range = xrange
	filter = itertools.ifilter
	map = itertools.imap
	zip = itertools.izip

def sync_with_stdio(sync=True):
	global input, flush
	if sync:
		flush = sys.stdout.flush
	else:
		sys.stdin = stream(sys.stdin.read())
		input = lambda : sys.stdin.readline().rstrip('\r\n')
		sys.stdout = stream()
		register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		s = input()
		cnt = s.count('L')
		if k >= cnt:
			print(2 * (n - 1) + 1)
		else:
			i = 0
			while i < n and s[i] == 'L':
				i += 1
			if i == n:
				if k == 0:
					print('0')
					continue
				else:
					print(2 * (k - 1) + 1)
					continue
			su = 1
			a = i
			v = []
			for j in range(a + 1, n):
				if s[j] == 'W':
					if a + 1 == j:
						su += 2
					else:
						su += 1
						v.append(j - a - 1)
					a = j
			v.sort()
			for i in v:
				if i > k:
					break
				cnt -= i
				k -= i
				su += 2 * i + 1
			if k:
				su += 2 * min(k, cnt)
			print(su)
sync_with_stdio(False)
main()


def print_arr(arr):
	for (i, ch) in enumerate(arr):
		if i == len(arr) - 1:
			print(ch)
		else:
			print(ch, end=' ')
	if not arr:
		print()

def run(arr):
	s = sum(arr)
	if s == 0:
		print('NO')
	elif s < 0:
		arr.sort()
		print('YES')
		print_arr(arr)
	else:
		arr.sort(reverse=True)
		print('YES')
		print_arr(arr)

def chess(s, k):
	l_count = s.count('L')
	if l_count <= k:
		return len(s) * 2 - 1
	interval_count = 1
	intervals = []
	start = 0
	wins = s.count('W') + k
	for i in range(len(s)):
		if s[i] == 'W':
			start = i
			break
	is_winning = True
	curr_lose_size = 0
	for i in range(start, len(s)):
		if is_winning and s[i] == 'L':
			is_winning = False
			curr_lose_size += 1
		elif not is_winning and s[i] == 'L':
			curr_lose_size += 1
		elif not is_winning and s[i] == 'W':
			is_winning = True
			interval_count += 1
			intervals.append(curr_lose_size)
			curr_lose_size = 0
	intervals.sort()
	for i in intervals:
		k -= i
		if k >= 0:
			interval_count -= 1
		else:
			break
	return wins * 2 - interval_count if wins > 0 else 0
n = int(input())
for _ in range(n):
	k = int(input().split()[1])
	s = input()
	s = list(s)
	print(chess(s, k))


import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7

def lcm(x, y):
	return x * y / gcd(x, y)

def fact(x, mod=mod):
	ans = 1
	for i in range(1, x + 1):
		ans = ans * i % mod
	return ans

def arr2D(n, m, default=0):
	lst = []
	for i in range(n):
		temp = [default] * m
		lst.append(temp)
	return lst

def sortDictV(x):
	return {k: v for (k, v) in sorted(x.items(), key=lambda item: item[1])}

def solve(n, k, lst):
	lCnt = lst.count('L')
	wCnt = 'W' in lst
	prescore = 0
	for i in range(n):
		if lst[i] == 'W':
			if i != 0 and lst[i - 1] == 'W':
				prescore += 2
			else:
				prescore += 1
	ans = []
	got = False
	cnt = 0
	for i in range(n):
		if got:
			if lst[i] == 'L':
				cnt += 1
			else:
				ans.append(cnt)
				cnt = 0
		if lst[i] == 'W':
			got = True
	ans = sorted(ans)
	ind = 0
	ans += [1]
	for i in range(len(ans) + 1):
		if ans[i] != 0:
			ind = i
			break
	ans = ans[ind:][:-1]
	i = 0
	while i < len(ans) and k >= ans[i]:
		prescore += ans[i] * 2 + 1
		k -= ans[i]
		lCnt -= ans[i]
		i += 1
	ind1 = i
	ind2 = 0
	ans1 = []
	got = False
	cnt1 = 0
	for i in range(n):
		if got:
			if lst[i] == 'L':
				cnt1 += 1
			elif cnt1 != 0:
				ans1.append(cnt1)
				cnt1 = 0
			if len(ans1) == ind1:
				ind2 = i
				break
		if lst[i] == 'W':
			got = True
	ind3 = ind2
	for i in range(ind2, n):
		if lst[i] == 'L':
			ind3 = i
			break
	cntAft = 0
	if wCnt:
		for i in range(ind3, n):
			if lst[i] == 'L':
				cntAft += 1
	cntBef = lCnt - cntAft
	if k > 0:
		prescore += 2 * min(cntAft, k)
		k -= min(cntAft, k)
		if k > 0:
			prescore += 2 * min(k - 1, cntBef - 1) + 1
			if wCnt:
				prescore += 1
	return prescore
for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	lst = input()
	print(solve(n, k, list(lst)))


for x in range(int(input())):
	(n, k) = map(int, input().split())
	string = list(input())
	lose = []
	count = 0
	(score, first, last) = (0, 0, 0)
	for i in range(n - 1):
		if string[i] == string[i + 1]:
			count += 1
			if i == n - 2:
				if string[i] == 'L':
					lose.append(count + 1)
				if string[i] == 'W':
					score = score + count * 2 + 1
				break
		elif string[i] == 'W':
			score = score + count * 2 + 1
			count = 0
			if i == n - 2:
				lose.append(1)
		else:
			lose.append(count + 1)
			count = 0
			if i == n - 2:
				score += 1
	if n == 1:
		if string[0] == 'W':
			score = 1
		else:
			last = 1
	else:
		if string[-1] == 'L' and lose:
			last = lose.pop()
		if string[0] == 'L' and lose:
			first = lose.pop(0)
	lose = sorted(lose)
	for i in lose:
		if k - i < 0:
			score = score + k * 2
			k = 0
			break
		else:
			k -= i
			score = score + i * 2 + 1
	if k >= last and score > 0:
		score = score + last * 2
		k -= last
	elif last > k and score > 0:
		score = score + k * 2
		k = 0
	elif last > 0 and k >= last:
		score = score + last * 2 - 1
		k -= last
	elif k > 0 and last > k:
		score = score + k * 2 - 1
		k = 0
	if k >= first and score > 0:
		score = score + first * 2
		k -= first
	elif first > k and score > 0:
		score = score + k * 2
		k = 0
	print(score)


import io
import os

def solve():
	(n, k) = map(int, input().split())
	A = input()
	segs = []
	(s, t) = (0, 0)
	while s < n and A[s] == 'L':
		s += 1
	head = (0, s)
	nn = n
	while nn >= 1 and A[nn - 1] == 'L':
		nn -= 1
	tail = (nn, n)
	while s < nn:
		if A[s] == 'W':
			s += 1
			continue
		t = s
		while t < nn and A[t] == 'L':
			t += 1
		segs.append((s, t))
		s = t
	segs.sort(key=lambda x: x[1] - x[0])
	B = list(A)
	for (s, t) in segs:
		if k <= 0:
			break
		w = min(t - s, k)
		B[s:s + w] = 'W' * w
		k -= w
	if k > 0 and tail[0] != n:
		(s, t) = tail
		w = min(t - s, k)
		B[s:s + w] = 'W' * w
		k -= w
	if k > 0 and head[1] > 0:
		(s, t) = head
		w = min(t - s, k)
		B[t - w:t] = 'W' * w
		k -= w
	score = 0
	for i in range(n):
		if i >= 1 and B[i - 1] == 'W' and (B[i] == 'W'):
			score += 2
			continue
		if B[i] == 'W':
			score += 1
			continue
	return score
TC = int(input())
for _ in range(TC):
	print(solve())


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(io.IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from itertools import groupby
T = int(input())
for _ in range(T):
	(N, K) = map(int, input().split())
	S = input()
	L_lens = []
	ans = 0
	for (wl, gr) in groupby(S):
		n = len(list(gr))
		if wl == 'L':
			L_lens.append(n)
		else:
			ans += n * 2 - 1
	l_cnt = sum(L_lens)
	if l_cnt == N:
		ans = K * 2 - 1
		if K == 0:
			ans = 0
		print(ans)
		continue
	k = min(K, l_cnt)
	if S[0] == 'L':
		del L_lens[0]
	if S[-1] == 'L':
		del L_lens[-1]
	L_lens.sort()
	ans += k * 2
	for l_len in L_lens:
		if k >= l_len:
			ans += 1
			k -= l_len
	print(ans)


t = int(input())

def solve(s, k):
	gaps = []
	last_pos = None
	if s.count('L') == len(s):
		if k:
			return k * 2 - 1
		else:
			return 0
	for (i, x) in enumerate(s):
		if x == 'W':
			if last_pos is not None:
				gaps.append((i - last_pos - 1, last_pos + 1, i))
			last_pos = i
	gaps.sort(reverse=True)
	score = 0
	while gaps and k:
		(width, start, end) = gaps.pop()
		if width <= k and width:
			score += 1
		k -= width
		score += width * 2
	if k:
		score += 2 * k
	return score
for case in range(t):
	(n, k) = map(int, input().split())
	s = input()
	k = min(k, s.count('L'))
	score = 0
	for (i, x) in enumerate(s):
		score += x == 'W'
		if x == 'W' and i > 0:
			score += s[i - 1] == 'W'
	print(score + solve(s, k))


from sys import stdin, stdout, setrecursionlimit
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log, log2
from random import seed, randint
from datetime import datetime
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from collections import defaultdict as dd
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def def_value():
	return 0

def def_inf():
	return inf

def atoi(s):
	return ord(s) - ord('a')

def inc(s, n=1):
	return chr((ord(s) - ord('a') + n) % 26 + ord('a'))
for _ in range(iinp()):
	(n, k) = mp()
	s = inp()
	win = s.count('W')
	if win == 0:
		print(max(2 * min(n, k) - 1, 0))
	else:
		dis = int(s[0] == 'W')
		for i in range(n - 1):
			if s[i] == 'L' and s[i + 1] == 'W':
				dis += 1
		gp = []
		i = 0
		while i < n:
			if s[i] == 'L':
				i += 1
			else:
				break
		while i < n:
			cnt = 0
			while i < n:
				if s[i] == 'L':
					cnt += 1
				else:
					break
				i += 1
			if cnt > 0:
				gp.append(cnt)
			i += 1
		if s[n - 1] == 'L' and len(gp) > 0:
			gp.pop()
		gp.sort()
		inc = 0
		ans = 0
		for i in gp:
			if inc + i <= k:
				inc += i
				ans += 1
			else:
				break
		if k + win >= n:
			print(2 * n - 1)
		else:
			print(2 * (win + k) - dis + ans)


from collections import deque
t = int(input())
while t:
	(n, k) = map(int, input().split())
	s = input()
	for x in range(n):
		if s[x] == 'W':
			break
	m = x
	u = 0
	d = deque()
	for y in range(x, n):
		if s[y] == 'L':
			u += 1
		if s[y] == 'W' and u > 0:
			d.append(u)
			u = 0
	b = u
	l = len(d)
	d = sorted(d)
	score = 0
	wins = 0
	for x in range(n):
		if s[x] == 'W':
			wins += 1
			if x > 0 and s[x - 1] == 'W':
				score += 2
			else:
				score += 1
	for x in range(l):
		if k >= d[x]:
			score = score + d[x] * 2 + 1
			k -= d[x]
		elif k > 0 and k < d[x]:
			score = score + k * 2
			k = 0
	if k > 0:
		if wins == 0:
			score = score + (k - 1) * 2 + 1
		elif m + b <= k:
			score = score + (m + b) * 2
		elif m + b > k:
			score = score + k * 2
	print(score)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(int(n))
	return l

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c
for xyz in range(0, int(input())):
	(n, k) = map(int, input().split())
	s = input()
	if k >= s.count('L'):
		print(2 * n - 1)
	elif s.count('W') == 0:
		print(max(0, 2 * k - 1))
	else:
		gaps = []
		streaks = 0
		i = s.index('W')
		while i < n:
			if s[i] == 'W':
				c = countcon(s, i)
				streaks += 1
				i += c
			else:
				c = countcon(s, i)
				gaps.append(c)
				i += c
		if s[-1] == 'L':
			gaps.pop()
		gaps.sort()
		gf = 0
		ans = 2 * s.count('W') - streaks
		t = k
		for i in range(0, len(gaps)):
			if gaps[i] > k:
				break
			else:
				gf += 1
				k -= gaps[i]
		ans += gf
		ans += t * 2
		print(ans)


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	s = list(input())
	mode = 0
	ls = []
	count = 0
	for i in range(n):
		if s[i] == 'W':
			if mode == 1:
				if count != 0:
					ls.append(count)
			mode = 1
			count = 0
		else:
			count += 1
	ls.sort()
	sum = 0
	prev = 'L'
	for i in range(n):
		if s[i] == 'W':
			if prev == 'W':
				sum += 2
			else:
				sum += 1
		prev = s[i]
	for x in ls:
		if x <= k:
			k -= x
			sum += 2 * x + 1
		else:
			sum += 2 * k
			k = 0
	count = 0
	for i in range(n):
		if s[i] == 'L':
			count += 1
		else:
			break
	for i in reversed(range(n)):
		if s[i] == 'L':
			count += 1
		else:
			break
	if count == 2 * n:
		sum += max(2 * min(k, n) - 1, 0)
	else:
		sum += 2 * min(k, count)
	print(sum)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	cntW = s.count('W')
	cntL = s.count('L')
	cnt = 0
	point = 0
	gap = []
	prevIndex = -1
	firstIndex = -1
	for i in range(n):
		if s[i] == 'W':
			cnt += 1
			if prevIndex == -1:
				prevIndex = i
				firstIndex = i
			elif i - prevIndex > 1:
				gap.append(i - prevIndex - 1)
			prevIndex = i
		elif cnt > 0:
			point += cnt * 2 - 1
			cnt = 0
	if s[-1] == 'W':
		point += cnt * 2 - 1
	gap.sort()
	j = 0
	while j < len(gap) and k > 0:
		if gap[j] <= k:
			point += 2 * gap[j] + 1
			k -= gap[j]
			cntL -= gap[j]
			j += 1
		else:
			point += 2 * k
			k = 0
	if j == len(gap) and k > 0:
		point += min(cntL, k) * 2
	if cntW == 0:
		point = min(cntL, k) * 2 - 1
	print(max(point, 0))


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
import sys
input = sys.stdin.readline
scanner = lambda : int(input())
string = lambda : input().rstrip()
get_list = lambda : list(read())
read = lambda : map(int, input().split())
get_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

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

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	if y == 0:
		return 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

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

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

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(moves, n):
	val = (moves + 1) // 2
	rem = moves - val
	sol = (val + 1) * (rem + 1)
	return sol < n

def sortSecond(val):
	return val[1]
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
alphs = 'abcdefghijklmnopqrstuvwxyz'
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect
import functools as fnt
from decimal import Decimal

def solve():
	(n, k) = read()
	tournaments = list(string())
	start = 0
	end = n - 1
	z = k
	while start < n and tournaments[start] != 'W':
		start += 1
	while end >= 0 and tournaments[end] != 'W':
		end -= 1
	lstart = INF
	lend = 0
	c = 0
	lengths = []
	countw = tournaments.count('W')
	countl = 0
	winning_streak = 0
	for i in range(start, end + 1):
		if tournaments[i] == 'L':
			lstart = min(lstart, i)
			c += 1
			countl += 1
		else:
			lend = i
			if c > 0:
				winning_streak += 1
				lengths.append(c)
				c = 0
				lstart = INF
	lengths.sort()
	winning_streak += 1
	gaps = 0
	c = 0
	for x in lengths:
		if c > k:
			break
		gaps += 1
		c += x
	if c > k:
		gaps -= 1
	print(max(0, 2 * min(countw + k, n) - winning_streak + gaps))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = scanner()
for i in range(t):
	solve()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	L = s.count('L')
	W = s.count('W')
	score = 0
	if s[0] == 'W':
		score += 1
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				score += 2
			else:
				score += 1
	start = False
	count = 0
	List = []
	for i in range(n):
		if start:
			if s[i] == 'W':
				if count:
					List.append(count)
					count = 0
			else:
				count += 1
		elif s[i] == 'W':
			start = True
	List.sort()
	if W:
		for i in List:
			if k:
				if k >= i:
					score += (i - 1) * 2 + 3
					k -= i
					L -= i
				else:
					score += k * 2
					k = 0
					L -= k
		if k:
			score += min(k, L) * 2
		print(score)
	elif k:
		print(min(k, L) * 2 - 1)
	else:
		print(0)


t = int(input())
for q in range(t):
	(n, k) = map(int, input().split())
	s = input()
	kol = []
	mas = []
	l = -1
	kz = 0
	for i in range(n):
		if s[i] == 'W':
			if l == -1:
				l = i
				r = i
			else:
				r = i
			mas.append(1)
		else:
			if l != -1:
				kol.append([l, r])
				l = -1
			mas.append(0)
	if l != -1:
		kol.append([l, r])
	ans = []
	for i in range(len(kol) - 1):
		ans.append(kol[i + 1][0] - kol[i][1] - 1)
	ans.sort()
	if kol == []:
		gh = 0
		if k > 0:
			gh += 1
			k -= 1
		gh += k * 2
		print(gh)
	else:
		gh = 0
		for i in kol:
			if i[0] == i[1]:
				gh += 1
			else:
				gh += 1 + (i[1] - i[0]) * 2
		for i in ans:
			z = i
			if k < z:
				break
			if z == 1:
				if k > 0:
					gh += 3
					k -= 1
					kz += 1
			else:
				gh += 3 + (z - 1) * 2
				k -= z
				kz += z
		dz = sum(mas) + kz
		dz = n - dz
		gh += min(k, dz) * 2
		print(gh)


import heapq
import collections
from math import log2
import itertools
from functools import lru_cache
from sys import setrecursionlimit as srl
srl(2 * 10 ** 6)
N = 200001

def amin(a, b):
	if b < a:
		a = b
	return a

def solve(n, k, a):
	w = 0
	W = 0
	ans = 0
	v = []
	cur = 0
	for i in range(n):
		if a[i] == 'W':
			if cur:
				v.append(cur)
				cur = 0
			w += 1
			ans += 1
			if W:
				ans += 1
			W = 1
		else:
			W = 0
			if w:
				cur += 1
	if not w:
		return max(2 * k - 1, 0)
	if k > n - w:
		k = n - w
	ans += 2 * k
	v.sort()
	for x in v:
		if x <= k:
			ans += 1
			k -= x
	return ans
t = int(input())
for i in range(1, t + 1):
	(n, k) = map(int, input().split())
	a = input()
	print(solve(n, k, a))


t = int(input())
for i in range(0, t):
	(n, m) = list(map(int, input().split()))
	z = input()
	a = [z[j] for j in range(0, n)]
	s = 0
	cw = 0
	q = 0
	b = []
	d = []
	for j in range(0, n):
		if a[j] == 'W':
			cw = cw + 1
			b.append(j)
			if q == 1:
				s = s + 2
			if q == 0:
				s = s + 1
			q = 1
		else:
			q = 0
	g = n - cw
	if m == 0:
		print(s)
		continue
	if cw == 0:
		print(2 * m - 1)
		continue
	elif g <= m:
		s = 1 + 2 * (n - 1)
	elif g > m:
		le = len(b)
		for j in range(1, le):
			c = b[j] - b[j - 1] - 1
			if c > 0:
				d.append(c)
		d.sort()
		le = len(d)
		for j in range(0, le):
			if d[j] <= m:
				s = s + 2 * d[j] + 1
				m = m - d[j]
			else:
				break
		s = s + 2 * m
	print(s)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	ans = 0
	init = s.count('L')
	for i in range(1, n):
		if s[i] == 'W' and s[i - 1] == 'W':
			ans += 2
		elif s[i] == 'W':
			ans += 1
	if s[0] == 'W':
		ans += 1
	if k == 0:
		print(ans)
		continue
	final = []
	tmp = s.find('W')
	count = 0
	for i in range(tmp + 1, n):
		if s[i] == 'L':
			count += 1
		else:
			final.append(count)
			count = 0
	tmp3 = []
	for i in final:
		if i != 0:
			tmp3.append(i)
	final = tmp3[:]
	final.sort()
	i = 0
	while k > 0 and i < len(final):
		if final[i] <= k:
			k -= final[i]
			ans += 2 * final[i]
			ans += 1
		else:
			ans += 2 * k
			k = 0
		i += 1
	if 'W' not in s:
		if k <= n:
			ans += 2 * k - 1
		else:
			ans += 2 * n - 1
	else:
		ans += 2 * min(k, init - sum(final))
	print(ans)


t = int(input())
for tt in range(t):
	(n, k) = map(int, input().split())
	s = input()
	pre = False
	cur = 0
	mid = []
	for (i, c) in enumerate(s):
		if c == 'W':
			if pre:
				if cur:
					mid.append(cur)
			else:
				begin = cur
			pre = True
			cur = 0
		else:
			cur += 1
	end = cur
	if end == n:
		ans = k * 2 - 1 if k else 0
	else:
		mid.sort()
		ans = 0
		for m in mid:
			if not k:
				break
			if k < m:
				ans += 2 * k
				k = 0
			else:
				ans += 2 * m + 1
				k -= m
		end = min(end, k)
		ans += end * 2
		k -= end
		begin = min(begin, k)
		ans += begin * 2
		k -= begin
		pre = False
		for (i, c) in enumerate(s):
			if c == 'W':
				ans += 2 if pre else 1
				pre = True
			else:
				pre = False
	print(ans)


import sys, math
N = int(input())
for i in range(N):
	(n, c) = list(map(int, sys.stdin.readline().strip().split()))
	g_arr = list(sys.stdin.readline().strip())
	l_arr = []
	(l, r) = (-1, -1)
	g_arr.append('W')
	for i in range(n + 1):
		if g_arr[i] == 'L' and l == -1:
			l = i
		if g_arr[i] == 'W' and l > -1:
			r = i - 1
			l_arr.append((l, r))
			(l, r) = (-1, -1)
	g_arr.pop()
	l_arr.sort(key=lambda a: a[1] - a[0] if a[0] > 0 and a[1] < n - 1 else math.inf)
	for i in l_arr:
		if i[0] == 0:
			j = i[1]
			while j >= i[0] and c > 0:
				g_arr[j] = 'W'
				c -= 1
				j -= 1
		else:
			j = i[0]
			while j <= i[1] and c > 0:
				g_arr[j] = 'W'
				c -= 1
				j += 1
		if c == 0:
			break
	(pts, w_pt) = (0, 1)
	for i in range(n):
		if g_arr[i] == 'W':
			pts += w_pt
			if w_pt == 1:
				w_pt = 2
		elif w_pt == 2:
			w_pt = 1
	print(pts)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	a = list(input())
	yes = 0
	if a[0] == 'W':
		ans = 1
		yes = 1
		c = 0
	else:
		ans = 0
		c = 1
	r = []
	first = 0
	for i in range(1, n):
		if a[i] == 'W' and a[i - 1] == 'W':
			ans += 2
		elif a[i] == 'W' and a[i - 1] == 'L' and (yes != 0):
			r.append(c)
			c = 0
			ans += 1
		elif a[i] == 'W' and a[i - 1] == 'L':
			first = c
			yes = 1
			ans += 1
			c = 0
		else:
			c += 1
	last = c
	if ans == 0:
		print(min(max(k * 2 - 1, 0), n * 2 - 1))
	else:
		r.sort()
		s = 0
		i = 0
		j = len(r)
		while i < j and s + r[i] <= k:
			s += r[i]
			ans += r[i] * 2 + 1
			i += 1
		k -= s
		if i < j:
			ans += k * 2
		else:
			ans += min(last * 2 + first * 2, k * 2)
		print(ans)


t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split(' ')]
	s = input()
	a = []
	cur = 0
	flag = False
	b = []
	w = 0
	for i in range(n):
		if s[i] == 'L':
			cur += 1
		else:
			w += 1
			if cur > 0:
				a.append(cur)
				cur = 0
	if cur > 0:
		a.append(cur)
	k = min(k, n - w)
	if s[0] == 'W':
		if s[-1] == 'W':
			b = a[:]
		else:
			b = a[:-1]
	elif s[-1] == 'W':
		b = a[1:]
	else:
		b = a[1:-1]
	b.sort()
	score = 2 * w - 1 - len(b)
	if score < 0:
		score = max(0, 2 * k - 1)
		print(score)
		continue
	for i in b:
		if k >= i:
			k -= i
			score += 2 * i + 1
		else:
			break
	score += 2 * k
	print(score)


for _ in range(int(input())):
	(N, K) = map(int, input().split())
	S = input()
	winning_steaks_cnt = wins = losses = 0
	losing_steaks = []
	for i in range(N):
		if S[i] == 'W':
			wins += 1
			if i == 0 or S[i - 1] == 'L':
				winning_steaks_cnt += 1
		if S[i] == 'L':
			losses += 1
			if i == 0 or S[i - 1] == 'W':
				losing_steaks.append(0)
			losing_steaks[-1] = losing_steaks[-1] + 1
	if K >= losses:
		print(2 * N - 1)
		continue
	if wins == 0:
		if K == 0:
			print(0)
		else:
			print(2 * K - 1)
		continue
	if S[0] == 'L':
		losing_steaks[0] = 100000000.0
	if S[-1] == 'L':
		losing_steaks[-1] = 100000000.0
	losing_steaks.sort()
	wins += K
	for ls in losing_steaks:
		if ls > K:
			break
		K -= ls
		winning_steaks_cnt -= 1
	print(2 * wins - winning_steaks_cnt)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	s = list(s)
	cw = 0
	w = []
	idx = -1
	cl = 0
	fw = -1
	lw = -1
	ans = 0
	for i in range(n):
		if s[i] == 'W':
			if i > 0 and s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
			if fw == -1:
				fw = i
			lw = i
			cw += 1
			if idx != -1:
				if i - idx - 1:
					w.append(i - idx - 1)
			idx = i
		else:
			cl += 1
	w.sort()
	for i in w:
		if k == 0:
			break
		if i <= k:
			k -= i
			ans += 2 * (i - 1) + 3
		else:
			ans += 2 * k
			k -= k
	if k > 0:
		if k >= cl:
			ans = 1 + (n - 1) * 2
		elif cw == 0:
			if k >= n:
				ans = 1 + (n - 1) * 2
				k = 0
			else:
				ans = 1 + (k - 1) * 2
				k = 0
		else:
			for i in range(lw + 1, n):
				if k == 0:
					break
				ans += 2
				k -= 1
			if k > 0:
				for i in range(fw - 1, -1, -1):
					if k == 0:
						break
					ans += 2
					k -= 1
	print(ans)


def solve():
	(n, k) = map(int, input().split())
	s = input()[:n]
	z = s.count('W')
	leftL = n - z
	if z == 0:
		if k != 0:
			print(1 + 2 * (k - 1))
		else:
			print(0)
	else:
		total = 0
		for i in range(n):
			if s[i] == 'W':
				if i - 1 >= 0:
					if s[i - 1] == 'W':
						total += 2
					else:
						total += 1
				else:
					total += 1
		cont_seg = []
		(fir, sec) = (-1, -1)
		for i in range(n):
			if s[i] == 'W':
				if fir == -1:
					fir = i
				else:
					sec = i
			if fir != -1 and sec != -1:
				temp = sec - fir - 1
				if temp > 0:
					cont_seg.append(temp)
				fir = sec
		cont_seg.sort()
		for i in cont_seg:
			if i <= k:
				total += 1 + i * 2
				k -= i
				leftL -= i
		if leftL != 0 and k != 0:
			if leftL <= k:
				total += leftL * 2
			elif leftL > k:
				total += k * 2
		print(total)
for _ in range(int(input())):
	solve()


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	s = list(input())
	Wcnts = min(s.count('W') + k, n)
	lStreaks = []
	isStart = True
	lStreakLen = 0
	for c in s:
		if c == 'W':
			isStart = False
			if lStreakLen > 0:
				lStreaks.append(lStreakLen)
			lStreakLen = 0
		elif isStart == False:
			lStreakLen += 1
	lStreaks.sort(reverse=True)
	while lStreaks and lStreaks[-1] <= k:
		k -= lStreaks[-1]
		lStreaks.pop()
	if Wcnts > 0:
		ans = 2 * Wcnts - (len(lStreaks) + 1)
	else:
		ans = 0
	print(ans)


import itertools

def remove_beginning(lst, bad):
	idx = 0
	while lst[idx] == bad:
		idx += 1
		if len(lst) == idx:
			break
	return idx

def solve():
	(n, k) = [int(x) for x in input().strip().split()]
	game_scores = list(input().strip())
	(win, lose) = ('W', 'L')
	first_good_pos = remove_beginning(game_scores, lose)
	first_range = first_good_pos
	game_scores = game_scores[first_good_pos:]
	game_scores.reverse()
	if not game_scores:
		return max(2 * min(k, first_range) - 1, 0)
	last_good_pos = remove_beginning(game_scores, lose)
	last_range = last_good_pos
	game_scores = game_scores[last_good_pos:]
	game_scores.reverse()
	assignable_points_from_list_ends = first_range + last_range
	lose_lengths = []
	for (key, group) in itertools.groupby(game_scores):
		lose_lengths.append([key, len(list(group))])
	initial_points = sum(map(lambda t: 0 if t[0] == lose else 2 * t[1] - 1, lose_lengths))
	lose_lengths = list(filter(lambda t: t > 0, map(lambda t: 0 if t[0] == win else t[1], lose_lengths)))
	if n == 1:
		if game_scores[0] == win:
			return 1
		return 1 if k == 1 else 0
	lose_lengths.sort()
	for l in lose_lengths:
		if k >= l:
			(k, initial_points) = (k - l, initial_points + 2 * (l - 1) + 3)
		else:
			(k, initial_points) = (0, initial_points + 2 * k)
	initial_points += 2 * min(k, assignable_points_from_list_ends)
	return initial_points
for _ in range(int(input().strip())):
	print(solve())


import re

def cal_base_score(input_string):
	W_list = re.findall('W+', input_string)
	score = sum([2 * (len(w) - 1) + 1 for w in W_list])
	return score
total_samples = int(input())
for i in range(total_samples):
	(length, modify) = map(int, input().split())
	string = input()
	w_count = string.count('W')
	l_count = length - w_count
	base_score = cal_base_score(string)
	if 'W' not in string:
		if modify == 0:
			print(0)
		else:
			print(2 * modify - 1)
	else:
		s = re.search('(W.*W)', string)
		if s is not None:
			s = s.group()
		else:
			s = ''
		stack = sorted(re.findall('L+', s), reverse=True)
		first_l_seg = re.match('L+', string)
		last_l_seg = re.match('L+', string[::-1])
		while modify > 0 and len(stack) > 0:
			seg = stack.pop()
			modify -= 1
			if seg == 'L':
				base_score += 3
			else:
				base_score += 2
				stack.append(seg.replace('L', '', 1))
		if first_l_seg is None:
			len_first = 0
		else:
			len_first = len(first_l_seg.group())
		if last_l_seg is None:
			len_last = 0
		else:
			len_last = len(last_l_seg.group())
		if modify > 0:
			for _ in range(len_first + len_last):
				base_score += 2
				modify -= 1
				if modify <= 0:
					break
		print(base_score)


for i in range(int(input())):
	(n, k) = map(int, input().split())
	lst = input()
	count = 0
	last = -1
	ans = []
	for i in range(len(lst)):
		if lst[i] == 'L':
			continue
		count += 1
		if last != -1 and last != i - 1:
			ans += [i - last - 1]
		last = i
	ans.sort()
	mx = len(ans) + 1
	for i in range(len(ans)):
		if k >= ans[i]:
			count += ans[i]
			k -= ans[i]
			mx -= 1
	print(max(0, min(2 * n - 1, (count + k) * 2 - mx)))


import os
import sys
from io import BytesIO, IOBase
_str = str
BUFSIZE = 8192

def str(x=b''):
	return x if type(x) is bytes else _str(x).encode()

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

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

def mpint():
	return map(int, sys.stdin.readline().split(' '))

def itg():
	return int(sys.stdin.readline())

def rindex(array, value):
	for i in range(len(array) - 1, -1, -1):
		if array[i] == value:
			return i
	raise ValueError('{} is not in list'.format(value))
from collections import Counter, defaultdict, deque
from itertools import accumulate

def solve():
	(n, k) = mpint()
	s = list(inp())
	w = s.count('W')
	L = n - w
	if w <= 1:
		return max(0, min(n, k + w) * 2 - 1)
	for i in range(1, n - 1):
		if not k:
			break
		if s[i] == 'L' and s[i - 1] == s[i + 1] == 'W':
			s[i] = 'W'
			k -= 1
			L -= 1
	ans = 1 if s[0] == 'W' else 0
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	lose = []
	c = 0
	for i in range(s.index('W') + 1, rindex(s, 'W') + 1):
		if s[i] == 'W':
			if c:
				lose.append(c)
				c = 0
		else:
			c += 1
	lose.sort(reverse=True)
	while k and lose:
		c = lose.pop()
		if k >= c:
			ans += c * 2 + 1
			k -= c
			L -= c
		else:
			ans += k * 2
			k = 0
	ans += min(k, L) * 2
	return ans
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
for _ in range(itg()):
	print(solve())


def solve():
	(n, k) = map(int, input().split())
	K = k
	s = list(input())
	if s.count('W') + k > n:
		print(2 * n - 1)
		return
	if s.count('W') == 0:
		print(min(k, n) * 2 - 1 if k != 0 else 0)
		return
	arr = []
	streak = 0
	i = 0
	while i < n:
		j = i
		while j < n and s[j] == s[i]:
			j += 1
		if s[i] == 'W':
			streak += 1
		elif 0 < i and j < n:
			arr.append(j - i)
		i = j
	arr.sort()
	for c in arr:
		if c > k:
			break
		streak -= 1
		k -= c
	print(2 * (K + s.count('W')) - streak)
	return
t = int(input())
for _ in range(t):
	solve()


t = int(input())
for case in range(t):
	(n, k) = [int(x) for x in input().split(' ')]
	s = input()
	score = int(s[0] == 'W')
	for i in range(1, n):
		if s[i - 1:i + 1] == 'WW':
			score += 2
		elif s[i - 1:i + 1] == 'LW':
			score += 1
	losses = s.count('L')
	if 'W' in s:
		s_losses = s.index('W')
		e_losses = n - 1 - s.rindex('W')
		m_losses = [len(x) for x in s[s_losses:s.rindex('W') + 1].split('W') if x]
		m_dict = {}
		for streak in m_losses:
			if streak in m_dict.keys():
				m_dict[streak] += 1
			else:
				m_dict[streak] = 1
		while m_dict and k > 0:
			y = min(m_dict.keys())
			if k < y:
				score += k * 2
				k = 0
			else:
				score += 2 * y + 1
				m_dict[y] -= 1
				if m_dict[y] == 0:
					del m_dict[y]
				k -= y
		ends = [x for x in sorted([s_losses, e_losses]) if x]
		for y in ends:
			if k < y:
				score += k * 2
				k = 0
			else:
				score += 2 * y
				k -= y
	else:
		score = max(2 * k - 1, 0)
	print(score)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from heapq import *
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 10 ** 9 + 7

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

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

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve(case):
	(n, k) = sep()
	a = list(inp())
	ll = []
	temp = -1
	j = 0
	while j < n:
		if a[j] == 'L':
			curr = 0
			i = j
			while i < n and a[i] == 'L':
				curr += 1
				i += 1
			if i != n:
				if j != 0:
					ll.append(curr)
			else:
				temp = curr
			j = i + 1
		else:
			j += 1
	if a.count('L') <= k:
		print(2 * n - 1)
		return
	if a.count('L') == n:
		print(2 * k - 1 if k > 0 else 0)
		return
	ll = sorted(ll)
	ans = 0
	for i in range(len(ll)):
		if k >= ll[i]:
			ans += 2 * ll[i] + 1
			k -= ll[i]
		else:
			ans += 2 * k
			k = 0
			break
	if temp != -1:
		ans += 2 * min(k, temp)
		k -= min(k, temp)
	ans += 2 * k
	f = False
	for i in range(n):
		if a[i] == 'L':
			f = False
		elif f:
			ans += 2
		else:
			f = True
			ans += 1
	print(ans)
testcase(int(inp()))


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	S = input()
	wins = S.count('W')
	if k >= n - wins:
		print(2 * n - 1)
		continue
	elif wins == 0 and k:
		print(2 * k - 1)
		continue
	score = 0
	good = []
	i = S.find('W')
	extra = i
	cnt = 0
	while i < n:
		if S[i] == 'L':
			cnt += 1
		else:
			score += 1
			if i > 0 and S[i - 1] == 'W':
				score += 1
			if cnt:
				good.append(cnt)
			cnt = 0
		i += 1
	extra += cnt
	good.sort()
	for j in good:
		if k >= j:
			score += 1 + 2 * j
			k -= j
		else:
			score += 2 * k
			k = 0
	if k:
		score += 2 * min(k, extra)
	print(score)


def solve():
	(n, k) = map(int, input().split())
	s = input()
	ans = 0
	prev = False
	c = []
	cc = 0
	for i in range(n):
		if s[i] == 'W':
			if cc:
				if cc != i:
					c.append(cc)
				cc = 0
			if prev:
				ans += 2
			else:
				ans += 1
			prev = True
		else:
			prev = False
			cc += 1
	c.sort()
	for i in range(len(c)):
		if c[i] <= k:
			k -= c[i]
			ans += c[i] * 2 + 1
	if 'W' in s:
		ans += k * 2
	else:
		ans += max(k * 2 - 1, 0)
	ans = min(ans, n * 2 - 1)
	print(ans)
t = int(input())
for _ in range(t):
	solve()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	Wstreak = wins = loss = 0
	Lstreak = []
	for i in range(n):
		if s[i] == 'W':
			wins += 1
			if i == 0 or s[i - 1] == 'L':
				Wstreak += 1
		elif s[i] == 'L':
			loss += 1
			if i == 0 or s[i - 1] == 'W':
				Lstreak.append(0)
			Lstreak[-1] += 1
	if k >= loss:
		print(2 * n - 1)
	elif wins == 0:
		if k == 0:
			print(0)
		else:
			print(2 * k - 1)
	else:
		if s[0] == 'L':
			Lstreak[0] = 100000000.0
		if s[-1] == 'L':
			Lstreak[-1] = 100000000.0
		Lstreak.sort()
		wins += k
		for i in Lstreak:
			if i > k:
				break
			k -= i
			Wstreak -= 1
		print(2 * wins - Wstreak)


import sys
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	i = 0
	l = []
	el = 0
	while i < n and s[i] == 'L':
		i += 1
		el += 1
	j = n - 1
	while j > i and s[j] == 'L':
		j -= 1
		el += 1
	if i > j:
		print(max(0, 2 * k - 1))
		continue
	ans = 0
	while i <= j:
		c = 0
		while i <= j and s[i] == 'W':
			i += 1
			c += 1
		ans += 2 * c - 1
		c = 0
		while i <= j and s[i] == 'L':
			i += 1
			c += 1
		if c != 0:
			l.append(c)
	l.sort()
	(i, le) = (0, len(l))
	while i < le and k > 0:
		if k >= l[i]:
			ans += 2 * l[i] + 1
		else:
			ans += 2 * k
		k -= l[i]
		i += 1
	print(ans + 2 * max(0, min(k, el)))


import io
import os
import sys
import math
input = sys.stdin.readline
mod = 10 ** 9 + 7
t = int(input())
for i in range(t):
	(x, y) = list(map(int, input().split()))
	arr = list(input().rstrip())
	c = 0
	w = 0
	seg = []
	score = 0
	left = 0
	for i in range(len(arr)):
		if arr[i] == 'W':
			if i > 0 and arr[i - 1] == 'W':
				score += 2
			else:
				score += 1
			if c != 0 and w != 0:
				seg.append(c)
			c = 0
			w += 1
		else:
			c += 1
			left += 1
	seg.sort()
	ans = 0
	for el in seg:
		if y >= el and left >= el:
			score += el * 2 + 1
			y -= el
			left -= el
	kg = min(y, left)
	if arr.count('W') == 0:
		print(max(0, kg * 2 - 1))
	else:
		print(max(0, score + 2 * kg))


import io
import os
import sys
import math
from operator import attrgetter
from typing import NamedTuple
from collections import deque
input = sys.stdin.readline

class Block(NamedTuple):
	size: int
	profit: int
	ratio: float
	is_begin: bool
	is_end: bool

def fill_gap(size, is_begin, is_end, k):
	take = min(size, k)
	inc = 2 * take
	if is_begin and (take == size or is_end):
		inc -= 1
	if not is_end and take == size:
		inc += 1
	return inc
T = int(input())
for t in range(T):
	(N, K) = map(int, input().split())
	S = input().strip()
	loss = win = 0
	L = []
	current_len = 0
	ans = 0
	for (i, s) in enumerate(S):
		if s == 'W':
			prev = S[i - 1] if i else 'L'
			ans += 2 if prev == 'W' else 1
			win += 1
			if current_len:
				profit = fill_gap(size=current_len, is_begin=current_len == i, is_end=False, k=N + 1)
				L.append(Block(current_len, profit, profit / current_len, current_len == i, False))
			current_len = 0
		else:
			current_len += 1
			loss += 1
	if current_len:
		profit = fill_gap(size=current_len, is_begin=current_len == N, is_end=True, k=N + 1)
		L.append(Block(current_len, profit, profit / current_len, is_begin=current_len == N, is_end=True))
	L.sort(key=lambda block: (block.ratio, -block.size), reverse=True)
	if K >= loss:
		print(N * 2 - 1)
		continue
	for block in L:
		if K == 0:
			break
		ans += fill_gap(block.size, block.is_begin, block.is_end, K)
		K -= min(K, block.size)
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	data = input()
	start = data.find('W')
	result = 0
	prev = False
	for x in data:
		if x == 'W':
			if prev:
				result += 2
			else:
				result += 1
			prev = True
		else:
			prev = False
	if start == -1:
		if k == 0:
			print(0)
		else:
			print(k * 2 - 1)
		continue
	gap_list = []
	end = start + 1
	if k > n - data.count('W'):
		k = n - data.count('W')
	cnt = 0
	for i in range(start + 1, n):
		if data[i] == 'L':
			cnt += 1
		if data[i - 1] == 'L' and data[i] == 'W':
			gap_list.append(cnt)
			cnt = 0
	gap_list.sort()
	for x in gap_list:
		if k >= x:
			result += 3 + 2 * (x - 1)
			k -= x
		else:
			break
	print(result + 2 * k)


import math
t = int(input())
for _ in range(t):
	nk = input().split()
	n = int(nk[0])
	k = int(nk[1])
	s = input()
	n_winning_steaks = 0
	n_wins = 0
	n_losses = 0
	losing_streaks = []
	for i in range(n):
		if s[i] == 'W':
			n_wins += 1
			if i == 0 or s[i - 1] == 'L':
				n_winning_steaks += 1
		if s[i] == 'L':
			n_losses += 1
			if i == 0 or s[i - 1] == 'W':
				losing_streaks.append(0)
			losing_streaks[-1] += 1
	if k >= n_losses:
		print(2 * n - 1)
		continue
	if n_wins == 0:
		if k == 0:
			print(0)
		else:
			print(2 * k - 1)
		continue
	if s[0] == 'L':
		losing_streaks[0] = math.inf
	if s[-1] == 'L':
		losing_streaks[-1] = math.inf
	losing_streaks.sort()
	n_wins += k
	for i in range(len(losing_streaks)):
		ls = losing_streaks[i]
		if ls > k:
			break
		k -= ls
		n_winning_steaks -= 1
	print(f'{2 * n_wins - n_winning_steaks}')


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log, trunc
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(n, kx) = lmp()
	s = inp()
	if s.count('W') == 0:
		print(max(0, 2 * kx - 1))
		continue
	c = 0
	l = 0
	t = False
	for i in s:
		if i == 'L':
			l += 1
			t = False
		elif t:
			c += 2
		else:
			t = True
			c += 1
	i = 0
	x = 0
	ml = []
	while i < n and s[i] == 'L':
		i += 1
	j = n - 1
	while j > -1 and s[j] == 'L':
		j -= 1
	for k in range(i, j + 1):
		if s[k] == 'L':
			x += 1
		elif x != 0:
			ml.append(x)
			x = 0
	ml.sort()
	for i in ml:
		if kx == 0:
			break
		if kx >= i:
			c += 2 * i + 1
			l -= i
			kx -= i
		else:
			c += 2 * kx
			l -= kx
			kx = 0
	if kx > 0 and l > 0:
		c += 2 * min(kx, l)
	print(c)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = []
	w = input()
	for j in w:
		s.append(j)
	p = k
	res = []
	j = 0
	while j < n:
		if s[j] == 'W':
			res.append(j)
		j += 1
	if len(res) == 0:
		j = 0
		while j < n:
			if p == 0:
				break
			s[j] = 'W'
			p += -1
			j += 1
	elif len(res) == 1:
		j = res[0] - 1
		while j >= 0:
			if p == 0:
				break
			s[j] = 'W'
			p += -1
			j += -1
		j = res[0] + 1
		while j < n:
			if p == 0:
				break
			s[j] = 'W'
			p += -1
			j += 1
	else:
		req = []
		j = 1
		while j < len(res):
			req.append([res[j] - res[j - 1], res[j - 1], res[j]])
			j += 1
		req.sort()
		l = 0
		while l < len(req):
			if p == 0:
				break
			j = req[l][1] + 1
			while j < req[l][2]:
				if p == 0:
					break
				s[j] = 'W'
				p += -1
				j += 1
			l += 1
		j = res[0] - 1
		while j >= 0:
			if p == 0:
				break
			s[j] = 'W'
			p += -1
			j += -1
		j = res[-1] + 1
		while j < n:
			if p == 0:
				break
			s[j] = 'W'
			p += -1
			j += 1
	j = 1
	ans = 0
	if s[0] == 'W':
		ans = 1
	while j < n:
		if s[j] == 'W' and s[j] == s[j - 1]:
			ans += 2
		elif s[j] == 'W':
			ans += 1
		j += 1
	print(ans)


t = int(input())
for it in range(0, t):
	(n, k) = tuple(list(map(int, input().split(' '))))
	results = [char for char in input()]
	initial_score = 0
	loss_amount = 0
	for i in range(0, len(results)):
		if i > 0 and results[i] == 'W' and (results[i - 1] == 'W'):
			initial_score += 1
		if results[i] == 'L':
			loss_amount += 1
	k = min(k, loss_amount)
	initial_score += n - loss_amount
	streak_increase_added_score = 2 * k
	if loss_amount == n and streak_increase_added_score > 0:
		streak_increase_added_score -= 1
	streak_diffs = []
	current_streak_diff = 0
	streak_found = 0
	for i in range(0, n):
		if results[i] == 'W':
			streak_found = True
			if current_streak_diff != 0:
				streak_diffs.append(current_streak_diff)
				current_streak_diff = 0
		if results[i] == 'L' and streak_found:
			current_streak_diff += 1
	sorted_streak_diffs = sorted(streak_diffs)
	disjoint_streak_decrease_added_score = 0
	for i in range(0, len(sorted_streak_diffs)):
		if k >= sorted_streak_diffs[i]:
			disjoint_streak_decrease_added_score += 1
			k -= sorted_streak_diffs[i]
		else:
			break
	final_score = initial_score + streak_increase_added_score + disjoint_streak_decrease_added_score
	print(final_score)


from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

@lru_cache(None)
def fact(x):
	if x < 2:
		return 1
	return fact(x - 1) * x

@lru_cache(None)
def per(i, j):
	return fact(i) // fact(i - j)

@lru_cache(None)
def com(i, j):
	return per(i, j) // fact(j)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 1
	res = 0
	for w in arr:
		res += w
		if res > x:
			res = w
		c += 1
	return c

def lowbit(n):
	return n & -n

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class smt:

	def __init__(self, l, r, arr):
		self.l = l
		self.r = r
		self.value = (1 << 31) - 1 if l < r else arr[l]
		mid = (l + r) // 2
		if l < r:
			self.left = smt(l, mid, arr)
			self.right = smt(mid + 1, r, arr)
			self.value &= self.left.value & self.right.value

	def setvalue(self, x, val):
		if self.l == self.r:
			self.value = val
			return
		mid = (self.l + self.r) // 2
		if x <= mid:
			self.left.setvalue(x, val)
		else:
			self.right.setvalue(x, val)
		self.value = self.left.value & self.right.value

	def ask(self, l, r):
		if l <= self.l and r >= self.r:
			return self.value
		val = (1 << 31) - 1
		mid = (self.l + self.r) // 2
		if l <= mid:
			val &= self.left.ask(l, r)
		if r > mid:
			val &= self.right.ask(l, r)
		return val

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d
t = N()
for i in range(t):
	(n, k) = RL()
	s = input()
	ans = 0
	for i in range(n):
		if s[i] == 'W':
			if i == 0:
				ans += 1
			else:
				ans += 1 + (s[i - 1] == 'W')
	if ans == 0:
		ans = 2 * k - 1 if k else 0
	else:
		arr = []
		for (ch, g) in groupby(s):
			l = len(list(g))
			arr.append((ch, l))
		res = 0
		c = Counter()
		for (i, (ch, l)) in enumerate(arr):
			if ch == 'L':
				if i == 0 or i == len(arr) - 1:
					res += l
				else:
					c[l] += 1
		for m in sorted(c.keys()):
			if k <= m * c[m]:
				(x, y) = divmod(k, m)
				ans += x * (2 * m + 1) + 2 * y
				k = 0
				break
			else:
				k -= m * c[m]
				ans += c[m] * (2 * m + 1)
		if k:
			if res:
				ans += min(res, k) * 2
				k = 0
	print(ans)


t = int(input())
for ii in range(t):
	(n, k) = map(int, input().split())
	s = input()
	a = [0] * n
	for i in range(n):
		if s[i] == 'W':
			if i == 0:
				a[i] = 1
			elif a[i - 1] != 0:
				a[i] = 2
			else:
				a[i] = 1
	stretch = []
	extras = []
	count = 0
	index = None
	for i in range(n):
		if a[i] == 0:
			if index == None:
				index = i
			count += 1
		else:
			if index is not None:
				if index == 0:
					extras.append((count, index))
				else:
					stretch.append((count, index))
			count = 0
			index = None
	if a[-1] == 0:
		extras.append((count, index))
	stretch.sort()
	extras.sort()
	cnt = 0
	ind = 0
	while cnt < k and ind < len(stretch):
		inti = stretch[ind][1]
		while cnt < k and inti < n:
			if a[inti] == 0:
				a[inti] = 1
				inti += 1
				cnt += 1
			else:
				break
		ind += 1
	ind = 0
	while cnt < k and ind < len(extras):
		inti = extras[ind][1]
		if inti != 0:
			while cnt < k and inti < n:
				if a[inti] == 0:
					a[inti] = 1
					inti += 1
					cnt += 1
				else:
					break
		else:
			while inti < n and a[inti] == 0:
				inti += 1
			if inti == n:
				inti = n - 1
			if a[inti] != 0:
				inti -= 1
			while cnt < k and inti > -1:
				if a[inti] == 0:
					a[inti] = 1
					inti -= 1
					cnt += 1
				else:
					break
		ind += 1
	for i in range(n):
		if a[i] != 0:
			if i == 0:
				pass
			elif a[i - 1] != 0:
				a[i] = 2
	print(sum(a))


def cal(s, n):
	pits = []
	wins = []
	pit = 0
	win = 0
	for c in s:
		if c == 'W':
			win += 1
			if pit > 0:
				pits.append(pit)
				pit = 0
		else:
			pit += 1
			if win > 0:
				wins.append(win)
				win = 0
	if win > 0:
		wins.append(win)
	if s[0] == 'L' and len(pits) > 0:
		pit += pits[0]
		pits = pits[1:]
	pits = sorted(pits)
	fliped = 0
	adt = 0
	for p in pits:
		if fliped + p <= n:
			fliped += p
			adt += 1
		else:
			pit += p
	if n >= fliped + pit:
		return len(s) * 2 - 1
	if len(wins) == 0:
		return max(min(n, len(s)) * 2 - 1, 0)
	return sum(wins) * 2 - len(wins) + fliped * 2 + adt + min(n - fliped, pit) * 2

def web():
	T = int(input())
	for t in range(1, T + 1):
		arr = [int(s) for s in input().split(' ')]
		c = arr[1]
		s = input()
		ans = cal(s, c)
		print(ans)

def file():
	x = open('p2_in.txt')
	T = int(x.readline())
	for t in range(1, T + 1):
		arr = [int(s) for s in x.readline().split(' ')]
		c = arr[1]
		s = x.readline()[:-1]
		ans = cal(s, c)
		print(ans)
web()


test = int(input())
for _ in range(test):
	(n, k) = map(int, input().split())
	arr = list(input())
	less = []
	over = []
	wins = 0
	last = False
	pre = 0
	found = False
	for i in range(n):
		if arr[i] == 'W':
			if last:
				wins += 2
			else:
				wins += 1
			if pre <= k and found:
				if pre > 0:
					less.append(pre)
			else:
				over.append(pre)
			found = True
			last = True
			pre = 0
		else:
			pre += 1
			last = False
	if pre:
		over.append(pre)
		pre = 0
	less.sort()
	ans = 0
	for i in range(len(less)):
		if less[i] <= k:
			ans += less[i] * 2 + 1
			k -= less[i]
		else:
			over.append(less[i])
	v = min(k, sum(over))
	if wins == 0:
		ans += max(v * 2 - 1, 0)
	else:
		ans += 2 * v
	print(ans + wins)


T = int(input())
for t in range(T):
	(N, K) = [int(_) for _ in input().split()]
	initK = K
	s = input()
	nb_l = len([c for c in s if c == 'L'])
	current_score = 0
	current_nb = 0
	current_c = None
	loss_group_sizes = []
	has_won = False
	for c in s:
		if c == current_c:
			current_nb += 1
			if c == 'W':
				current_score += 2
			continue
		if current_c == 'L' and has_won:
			loss_group_sizes.append(current_nb)
		current_nb = 1
		current_c = c
		if c == 'W':
			current_score += 1
			has_won = True
	loss_group_sizes = sorted(loss_group_sizes)
	i = 0
	while K > 0 and i < len(loss_group_sizes):
		if K >= loss_group_sizes[i]:
			current_score += 2 * loss_group_sizes[i] + 1
			K -= loss_group_sizes[i]
		else:
			break
		i += 1
	left_l = nb_l - (initK - K)
	if 'W' in s:
		current_score += 2 * min(K, left_l)
	else:
		current_score += max(0, 2 * min(K, left_l) - 1)
	print(current_score)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	binstr = list(input())
	losearr = []
	current = 0
	active = 0
	wincntr = 0
	for result in binstr:
		if result == 'L':
			if active:
				wincntr += active
				active = 0
			current += 1
		elif current:
			losearr.append(current)
			current = 0
			active += 1
		elif active:
			active += 2
		else:
			active += 1
	wincntr += active
	start = 0
	if current:
		start += current
	if binstr[0] == 'L' and losearr:
		start += losearr[0]
		del losearr[0]
	losearr.sort()
	for rest in losearr:
		if k >= rest:
			wincntr += rest * 2 + 1
			k -= rest
		else:
			wincntr += k * 2
			k = 0
			break
	if k:
		if k >= start:
			if wincntr:
				wincntr += 2 * start
			else:
				wincntr += 2 * start - 1
		elif wincntr:
			wincntr += k * 2
		else:
			wincntr += k * 2 - 1
	print(wincntr)


import sys
from sys import stdin, stdout

def II():
	return int(stdin.readline())

def IP():
	return map(int, stdin.readline().split())

def solve():
	(n, k) = IP()
	s = input()
	cnt = s.count('W')
	if k == 0:
		ans = 0
		last = 'L'
		for ele in s:
			if ele == 'W' and last == 'W':
				ans += 2
			elif ele == 'W' and last == 'L':
				ans += 1
			last = ele
		print(ans)
		return
	elif cnt == 0:
		print(1 + 2 * (k - 1))
		return
	else:
		new = [0] * n
		(first, last) = (2 * n, -1)
		for i in range(n):
			new[i] = s[i]
			if s[i] == 'W':
				first = min(first, i)
				last = max(last, i)
		pq = []
		if first != last:
			llast = first
			for i in range(first + 1, last + 1, 1):
				if s[i] == 'W':
					pq.append([i - llast - 1, llast])
					llast = i
			pq.sort()
			i = 0
			nn = len(pq)
			while k > 0 and i < nn:
				(lenn, strt) = pq[i]
				end = strt + lenn + 1
				for j in range(strt + 1, end):
					if k > 0:
						new[j] = 'W'
						k -= 1
					else:
						break
				i += 1
		if k > 0:
			if s[last - 1] == 'W':
				for i in range(last + 1, n):
					if k > 0:
						new[i] = 'W'
						k -= 1
					else:
						break
				for i in range(first - 1, -1, -1):
					if k > 0:
						new[i] = 'W'
						k -= 1
					else:
						break
			else:
				for i in range(first - 1, -1, -1):
					if k > 0:
						new[i] = 'W'
						k -= 1
					else:
						break
				for i in range(last + 1, n):
					if k > 0:
						new[i] = 'W'
						k -= 1
					else:
						break
		ans = 0
		last = 'L'
		for ele in new:
			if ele == 'W' and last == 'W':
				ans += 2
			elif ele == 'W' and last == 'L':
				ans += 1
			last = ele
		print(ans)
		return
t = II()
for i in range(t):
	solve()


def solve():
	(x, y) = map(int, input().split())
	s = list(input())
	v = []
	ind = -1
	ct = 0
	st = 0
	for n in range(len(s)):
		if s[n] == 'L':
			if st:
				if ind == -1:
					ind = n
				ct += 1
		else:
			if ct:
				v.append([ct, ind])
				ct = 0
				ind = -1
			st = 1
	v.sort(key=lambda x: x[0])
	for n in v:
		for k in range(n[1], n[1] + n[0]):
			if y:
				s[k] = 'W'
				y -= 1
	id = 0
	for n in range(x):
		if s[n] == 'L':
			id += 1
		if s[n] == 'W':
			break
	id -= 1
	while id >= 0 and y:
		s[id] = 'W'
		id -= 1
		y -= 1
	id = x - 1
	while s[id] == 'L' and id > 0:
		id -= 1
	id += 1
	while id < x and y:
		s[id] = 'W'
		id += 1
		y -= 1
	res = 0
	st = 0
	for n in s:
		if n == 'W':
			if st == 0:
				res += 1
				st = 1
			else:
				res += 2
		else:
			st = 0
	print(res)
for _ in range(int(input())):
	solve()


import sys, os, io

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

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	for _ in range(ri()):
		(n, k) = ria()
		s = rs()
		consgaps = []
		conswins = []
		currconsgaps = 0
		currconswins = 0
		prevscore = 0
		for i in range(n):
			if s[i] == 'W':
				if i - 1 >= 0 and s[i - 1] == 'W':
					prevscore += 2
				else:
					prevscore += 1
		(L, R) = (0, n - 1)
		for i in range(n):
			if s[i] == 'W':
				L = i
				break
		for i in range(n - 1, -1, -1):
			if s[i] == 'W':
				R = i
				break
		ps = s
		s = s[L:R + 1]
		if k == 0:
			print(prevscore)
		elif prevscore == 0:
			print(2 * min(n, k) - 1)
		else:
			ngapsleftovers = L + n - 1 - R
			for i in range(len(s)):
				if s[i] == 'W':
					if currconsgaps > 0:
						consgaps.append(currconsgaps)
					currconswins += 1
					currconsgaps = 0
				else:
					if currconswins > 0:
						conswins.append(currconswins)
					currconswins = 0
					currconsgaps += 1
			if currconsgaps > 0:
				consgaps.append(currconsgaps)
			if currconswins > 0:
				conswins.append(currconswins)
			z = sorted(consgaps)
			newscore = prevscore
			for i in z:
				if k - i < 0:
					newscore += 2 * k
					k = 0
					break
				else:
					newscore += 2 * i + 1
					k -= i
			if k > 0:
				newscore += 2 * min(ngapsleftovers, k)
			print(newscore)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


nums = int(input().strip())
for _ in range(nums):
	(n, k) = map(int, input().strip().split())
	s = input().strip()
	cur_score = 0
	l_part = []
	cur_num = 0
	l_count = w_count = 0
	for (i, v) in enumerate(s):
		if v == 'W':
			w_count += 1
			if i > 0 and s[i - 1] == 'W':
				cur_score += 2
				continue
			elif i > 0 and s[i - 1] == 'L':
				l_part.append(cur_num)
				cur_num = 0
			cur_score += 1
		else:
			cur_num += 1
			l_count += 1
	if cur_num:
		l_part.append(cur_num)
	if k >= l_count:
		print(2 * len(s) - 1)
	elif l_part:
		(start, end) = (0, len(l_part))
		if s[0] == 'L':
			start += 1
		if s[-1] == 'L':
			end -= 1
		arr = sorted(l_part[start:end])
		for i in range(len(arr)):
			if k >= arr[i]:
				cur_score += 2 * arr[i] + 1
				k -= arr[i]
			else:
				break
		res = cur_score + k * 2
		if w_count == 0:
			res -= 1
		print(max(res, 0))
	else:
		print(cur_score)


from collections import deque
from collections import OrderedDict
import math
import sys
import os
import threading
import bisect
import operator
import heapq
from atexit import register
from io import BytesIO
import io
from sys import stdin, stdout
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
input = lambda : sys.stdin.readline().rstrip('\r\n')

def printEr(ar1):
	for i in range(len(ar1)):
		print(ar1[i], end=' ')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	tK = k
	s = input()
	if n == 1:
		if s[0] == 'L' and k == 0:
			print(0)
		else:
			print(1)
		continue
	if k == 1 and s.count('L') == n:
		print(1)
		continue
	if s.count('L') <= k:
		print(2 * n - 1)
		continue
	if s.count('W') == 0 and k != 0:
		print(k * 2 - 1)
		continue
	dp = [0] * (n + 1)
	dp[0] = 1 if s[0] == 'L' else 0
	conLost = []
	afWin = False
	if s[0] == 'W':
		afWin = True
	for i in range(1, len(s)):
		if s[i] == 'L':
			dp[i] = dp[i - 1] + 1
		elif dp[i - 1] != 0:
			if afWin == True:
				conLost.append(dp[i - 1])
			else:
				afWin = True
	conLost.sort()
	s = s + 'L'
	conWin = 0
	for i in range(1, n + 1):
		if s[i] == 'L' and s[i - 1] == 'W':
			conWin += 1
	for i in range(len(conLost)):
		if conLost[i] <= k:
			conWin -= 1
			k -= conLost[i]
		else:
			break
	answer = 2 * (tK + s.count('W')) - conWin
	print(answer)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	l = list(s)
	i = 0
	temp = []
	while i < n:
		if l[i] == 'W' and i + 1 < n and (l[i + 1] == 'W'):
			i += 1
		elif l[i] == 'W':
			j = i + 1
			while j < n and l[j] == 'L':
				j += 1
			if j != n:
				temp.append([j - i - 1, i + 1, j])
			i = j
		else:
			i += 1
	temp.sort()
	for i in range(len(temp)):
		cur = temp[i]
		for j in range(cur[1], cur[2]):
			if k == 0:
				break
			l[j] = 'W'
			k -= 1
		if k == 0:
			break
	i = 0
	while i < n:
		if k > 0:
			if l[i] == 'W':
				cur = i + 1
				while k > 0 and cur < n and (l[cur] == 'L'):
					l[cur] = 'W'
					cur += 1
					k -= 1
				i = cur
			else:
				i += 1
		else:
			break
	i = n - 1
	while i >= 0:
		if k > 0:
			if l[i] == 'W':
				cur = i - 1
				while k > 0 and cur >= 0 and (l[cur] == 'L'):
					l[cur] = 'W'
					cur -= 1
					k -= 1
				i = cur
			else:
				i -= 1
		else:
			break
	for i in range(n):
		if k > 0:
			if l[i] == 'L':
				l[i] = 'W'
				k -= 1
		else:
			break
	c = 0
	if l[0] == 'W':
		c += 1
	for i in range(1, n):
		if l[i - 1] == 'W' and l[i] == 'W':
			c += 2
		elif l[i] == 'W':
			c += 1
	print(c)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = ' ' + input()
	q = s.count('L')
	if q <= m:
		print(max(0, 2 * n - 1))
	elif q == len(s) - 1:
		print(max(0, 2 * m - 1))
	else:
		x = 0
		y = 0
		C = []
		for i in range(1, len(s)):
			if s[i - 1] == 'W' and s[i] == 'L':
				x = 1
			elif s[i - 1] == 'L' and s[i] == 'L' and (x != 0):
				x += 1
			elif s[i] == 'L':
				y += 1
			elif s[i - 1] == 'L' and s[i] == 'W':
				if x != 0:
					C.append(x)
				x = 0
		if x != 0:
			y += int(x)
		C.sort()
		Ans = 0
		for i in range(len(C)):
			if m >= C[i]:
				Ans += C[i] * 2 + 1
				m -= C[i]
		Ans += m * 2
		for i in range(1, len(s)):
			if s[i] == 'W':
				if s[i - 1] == 'W':
					Ans += 2
				else:
					Ans += 1
		print(Ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	li = []
	cnt = 0
	ans = 0
	lose = 0
	first = True
	for i in range(n):
		if s[i] == 'W':
			if not first and cnt > 0:
				li.append(cnt)
			cnt = 0
			if i > 0 and s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
			first = False
		else:
			lose += 1
			cnt += 1
	li.sort()
	k = min(lose, k)
	for i in li:
		if k < i:
			break
		ans += 2 * i + 1
		k -= i
	ans += k * 2
	if lose == n and k > 0:
		ans -= 1
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	a = []
	prev = -1
	for i in range(n):
		if s[i] == 'W':
			if prev != -1 and i != prev + 1:
				a.append((prev, i - 1))
			prev = i
	a.sort(key=lambda x: x[1] - x[0])
	ans = 0 if s[0] == 'L' else 1
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	for i in range(len(a)):
		ln = a[i][1] - a[i][0]
		if k >= ln:
			ans += ln * 2 + 1
			k -= ln
		else:
			ans += k * 2
			k = 0
	lf = s.find('W')
	if lf == -1:
		ans = k * 2 - 1
	else:
		ans += min(k, lf) * 2
		k -= min(k, lf)
		rf = s.rfind('W')
		ans += min(k, n - rf - 1) * 2
	print(max(0, ans))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	lnth = sorted(map(len, s.strip('L').split('W')), reverse=True)
	m = len(lnth) + k - 1
	while lnth and lnth[-1] <= k:
		k -= lnth.pop()
	print((2 * min(n, m) - len(lnth) or 1) - 1)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(input())
	(cont, edge) = ([], [])
	last = True
	(wCnt, lCnt, ans) = (0, 0, 0)
	for i in range(n):
		if l[i] == 'L':
			if wCnt > 0:
				ans += wCnt * 2 - 1
				wCnt = 0
			lCnt += 1
		else:
			if i == lCnt and i:
				edge.append(lCnt)
			elif lCnt > 0:
				cont.append(lCnt)
			wCnt += 1
			lCnt = 0
	if lCnt:
		edge.append(lCnt)
	if wCnt:
		ans += wCnt * 2 - 1
	cont.sort()
	edge.sort()
	if ans == 0:
		lCnt = min(k, lCnt)
		print(max(lCnt * 2 - 1, 0))
		continue
	for i in cont:
		if k == 0:
			break
		if k > i:
			ans += 2 * i + 1
			k -= i
		elif k < i:
			ans += 2 * k
			k = 0
		else:
			ans += 2 * i + 1
			k = 0
	for i in edge:
		if k == 0:
			break
		if k >= i:
			ans += i * 2
			k -= i
		else:
			ans += k * 2
			k = 0
	print(ans)


from collections import Counter as C

def mp():
	return map(int, input().split())

def it():
	return int(input())
for _ in range(it()):
	(n, k) = mp()
	l = list(input())
	c = C(l)
	ans = 0
	if c['L'] <= k:
		ans = 2 * n - 1
		print(ans)
	elif 'W' not in l:
		print(max(min(k, n) * 2 - 1, 0))
	else:
		sm = c['W']
		v = []
		indx = l.index('W')
		for i in range(indx + 1, n):
			if l[i] == 'W':
				v.append(i - indx - 1)
				indx = i
		v.sort()
		for i in v:
			if k >= i:
				sm += 2 * i + 1
				k -= i
		if k > 0:
			sm += 2 * k
		print(sm)


l = []
from collections import Counter
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(input())
	d = dict(Counter(a))
	if 'L' not in d:
		d['L'] = 0
	if 'K' not in d:
		d['K'] = 0
	if d['L'] <= k:
		l.append(1 + (n - 1) * 2)
	elif d['L'] == n and k != 0:
		l.append(1 + 2 * (k - 1))
	elif d['L'] == n and k == 0:
		l.append(0)
	else:
		s = []
		count = 0
		for i in range(n):
			if a[i] == 'L':
				count = count + 1
			elif i != 0:
				if a[i - 1] == 'L':
					s.append(count)
					count = 0
		if a[0] == 'L':
			s = s[1:]
		s.sort()
		sum = 0
		i = 0
		flag = 1
		while k > 0 and i < len(s):
			k = k - s[i]
			if k < 0:
				k = k + s[i]
				break
			else:
				sum = sum + 2 * s[i] + 1
			i = i + 1
		if k != 0:
			sum = sum + 2 * k
		s = []
		count = 0
		for i in range(n):
			if a[i] == 'W':
				count = count + 1
			elif i != 0:
				if a[i - 1] == 'W':
					s.append(count)
					count = 0
		if a[-1] == 'W':
			s.append(count)
		s1 = 0
		for i in s:
			s1 = s1 + 2 * i - 1
		l.append(sum + s1)
for i in l:
	print(i)


for bleh in range(int(input())):
	a = list(map(int, input().strip().split(' ')))[1]
	b = input()
	w = b.count('W')
	if w == 0:
		if a > 0:
			print(2 * a - 1)
		else:
			print(0)
	else:
		w = 0
		wt = False
		lcout = 0
		if b[0] == 'L':
			lcout = -1
		c = []
		d = []
		for i in b:
			if i == 'W':
				if wt:
					w += 2
				else:
					if lcout > 0:
						if lcout % 2 == 1:
							d.append(lcout)
						else:
							c.append(lcout)
						lcout = 0
					wt = True
					w += 1
			else:
				if wt:
					wt = False
				lcout += 2
		if lcout > 0:
			d.append(lcout - 1)
		c.sort()
		d.sort()
		for j in c:
			if j // 2 > a:
				w += 2 * a
				a = 0
				break
			else:
				w += j + 1
				a -= j // 2
		for j in d:
			if j // 2 + j % 2 > a:
				w += 2 * a
				break
			else:
				w += j + 1
				a -= j // 2 + j % 2
		print(w)


from sys import stdin, stdout
from os import path
if path.exists('input.txt'):
	stdin = open('input.txt', 'r')
	stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

	def S():
		return stdin.readline().rstrip()

	def Sn():
		return stdin.readline().split(' ')

def f(n, k, s):
	wins = loss = 0
	win_streak = 0
	lose_streaks = []
	for i in range(n):
		if s[i] == 'W':
			wins += 1
			if i == 0 or s[i - 1] == 'L':
				win_streak += 1
		else:
			loss += 1
			if i == 0 or s[i - 1] == 'W':
				lose_streaks.append(0)
			lose_streaks[-1] += 1
	if k >= loss:
		return 2 * n - 1
	if wins == 0:
		if k == 0:
			return 0
		return 2 * k - 1
	if s[0] == 'L':
		lose_streaks[0] = 1000000000.0
	if s[-1] == 'L':
		lose_streaks[-1] = 1000000000.0
	wins += k
	lose_streaks.sort()
	for i in lose_streaks:
		if i > k:
			break
		k -= i
		win_streak -= 1
	return 2 * wins - win_streak

def func():
	st = ''
	t = I()
	for _ in range(t):
		(n, k) = In()
		s = input()
		st = '\n'.join((st, str(f(n, k, s))))
	print(st.lstrip())
func()


t = int(input())
tests = []
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	tests.append([n, k, s])
for test in tests:
	(n, k, s) = test
	result = 0
	w = s.count('W')
	if w == 0:
		if k == 0:
			print(0)
		else:
			print(min(n, k) * 2 - 1)
		continue
	results = []
	for x in s:
		if results and results[-1][0] == x:
			results[-1][1] += 1
		else:
			results.append([x, 1])
	first_loses = 0
	if results[0][0] == 'L':
		first_loses = results[0][1]
		results.pop(0)
	last_loses = 0
	if results[-1][0] == 'L':
		last_loses = results[-1][1]
		results.pop()
	loses = []
	for (x, y) in results:
		if x == 'W':
			result += 2 * y - 1
		else:
			loses.append([x, y])
	loses.sort()
	for (x, y) in loses:
		if x == 'L':
			if k >= y:
				result += 2 * y + 1
				k -= y
			else:
				result += 2 * k
				k = 0
				break
	if last_loses > 0:
		if k >= last_loses:
			result += 2 * last_loses
			k -= last_loses
		else:
			result += 2 * k
			k = 0
	if first_loses > 0:
		if k >= first_loses:
			result += 2 * first_loses
		else:
			result += 2 * k
	print(result)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = input()
	b = []
	b1 = []
	c = []
	t = 0
	count = 0
	ans = 0
	m = n - 1
	if a[0] == 'L':
		while t < n and a[t] == 'L':
			count += 1
			t += 1
		b1.append(count)
		count = 0
	if a[-1] == 'L':
		while m >= 0 and a[m] == 'L':
			count += 1
			m -= 1
		b1.append(count)
		count = 0
	while t <= m:
		if a[t] == 'W':
			while t <= m and a[t] == 'W':
				count += 1
				t += 1
			c.append(count)
			count = 0
		else:
			while t <= m and a[t] == 'L':
				count += 1
				t += 1
			b.append(count)
			count = 0
	for i in c:
		ans += 2 * i - 1
	b.sort()
	if b1 and b1[-1] == n:
		ans += max(min(n, k) * 2 - 1, 0)
	else:
		for i in b:
			if i <= k:
				ans += 2 * i + 1
				k -= i
			else:
				ans += k * 2
				k = 0
			if not k:
				break
		if k and b1:
			ans += min(sum(b1), k) * 2
	print(ans)


import sys
from heapq import *

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def string(s):
	return ''.join(s)

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j):
	return 0 <= i < n and 0 <= j < m and (a[i][j] != '.')

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()
while t > 0:
	t -= 1
	(n, k) = mi()
	s = si()
	a = [0] * n
	ans = 0
	for i in range(n):
		if s[i] == 'W':
			a[i] += 1
			if i > 0 and a[i - 1]:
				ans += 2
			else:
				ans += 1
	l = []
	d = []
	prev = -1
	for i in range(n):
		if a[i]:
			if prev == -1 and i:
				d.append([1, i])
			elif i and i - prev - 1:
				d.append([0, i - prev - 1])
			prev = i
	if prev != n - 1:
		d.append([1, n - prev - 1])
	if a.count(1) == 0:
		print(1 + 2 * (k - 1) if k > 0 else 0)
		continue
	d.sort()
	for i in range(len(d)):
		if k - d[i][1] >= 0:
			ans += d[i][1] * 2
			if d[i][0] == 0:
				ans += 1
			k -= d[i][1]
		elif k:
			ans += k * 2
			k = 0
	print(ans)


t = int(input())
for t1 in range(t):
	(n, final) = [int(n1) for n1 in input().split()]
	s = list(str(input()))
	d = []
	k = []
	count = 0
	if s[0] == 'W':
		count = 1
	else:
		count = 0
	i = 0
	first = -1
	earlier_count = 0
	prev = 'L'
	while i < len(s):
		if s[i] == 'W':
			if first == -1:
				first = i
			if prev == 'W':
				earlier_count = earlier_count + 2
			else:
				earlier_count = earlier_count + 1
			d1 = -1
			if i + 1 < n:
				for j in range(i + 1, n):
					if s[j] == 'W':
						d1 = j - i - 1
						break
				if d1 > 0:
					d.append(d1)
					k.append(2)
					prev = 'L'
				elif d1 == -1:
					d.append(n - 1 - i)
					k.append(3)
					prev = 'L'
				else:
					prev = 'W'
				i = j
			else:
				i = i + 1
		else:
			prev = 'L'
			i = i + 1
	if first != 0 and first != -1:
		d.append(first - 0)
		k.append(3)
	if k != []:
		(k, d) = zip(*sorted(zip(k, d)))
		k = list(k)
		d = list(d)
		sum1 = 0
		sum2 = earlier_count
		for i in range(len(d)):
			if final >= sum1 + d[i]:
				sum1 = sum1 + d[i]
				if k[i] == 2:
					sum2 = sum2 + (2 * d[i] + 1)
				else:
					sum2 = sum2 + 2 * d[i]
			else:
				sum2 = sum2 + 2 * (final - sum1)
				sum1 = sum1 + (final - sum1)
				break
		print(sum2)
	elif s[0] == 'L':
		print(max(0, 2 * final - 1))
	else:
		print(earlier_count)


def solve():
	(n, k) = map(int, input().split())
	s = input()
	wn = 0
	for c in s:
		if c == 'W':
			wn += 1
	ln = 0
	c = 0
	while c < n and s[c] == 'L':
		c += 1
		ln += 1
	a = c
	c = len(s) - 1
	ln = 0
	while c >= 0 and s[c] == 'L':
		c -= 1
		ln += 1
	b = c
	ln = 0
	d = [0 for _ in range(n)]
	for i in range(a, b + 1):
		if s[i] == 'L':
			ln += 1
		else:
			d[ln] += 1
			ln = 0
	ls = 0
	K = k
	for i in range(1, len(d)):
		mn = min(k // i, d[i])
		ls += d[i] - mn
		k = k - mn * i
	score = 2 * min(n, wn + K) - (ls + 1)
	score = max(0, score)
	print(score)

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(input())
	f = False
	d = 0
	cntt = 0
	temp = []
	for (i, c) in enumerate(a):
		if c == 'W':
			if f and cntt != 0:
				temp.append((cntt, d))
				cntt = 0
			elif f == False:
				f = True
		else:
			if cntt == 0 and f:
				d = i
			if f:
				cntt += 1
	temp.sort()
	for (x, y) in temp:
		if k > x:
			a[y:y + x] = ['W'] * x
			k -= x
		else:
			a[y:y + k] = ['W'] * k
			k = 0
			break
	f = False
	for (i, c) in enumerate(a):
		if k == 0:
			break
		if f:
			if c == 'L':
				a[i] = 'W'
				k -= 1
				if k == 0:
					break
		elif c == 'W':
			dist = i
			f = True
	if k > 0 and f:
		if dist >= k:
			a[dist - k:dist] = ['W'] * k
		else:
			a[0:dist] = ['W'] * dist
	elif k > 0:
		for (i, c) in enumerate(a):
			if c == 'L':
				a[i] = 'W'
				k -= 1
				if k == 0:
					break
	ans = 0
	p = False
	for c in a:
		if p == False and c == 'W':
			ans += 1
			p = True
		elif p and c == 'W':
			ans += 2
		else:
			p = False
	print(ans)


t = int(input())
for case in range(t):
	(n, k) = map(int, input().split())
	s = input().split()[0]
	prev = 'L'
	score = 0
	curr = 0
	l = []
	foundW = False
	for i in range(n):
		if s[i] == 'W':
			foundW = True
			if curr != 0:
				l.append(curr)
			curr = 0
			if prev == 'L':
				score += 1
			else:
				score += 2
		else:
			curr += 1
		prev = s[i]
	if curr != 0:
		l.append(curr)
	if len(l) == 0:
		print(score)
		continue
	(beg, end) = (False, False)
	if s[0] == 'L':
		beg = True
	if s[n - 1] == 'L':
		end = True
	if foundW == False:
		score = max(2 * k - 1, 0)
		print(score)
		continue
	bonus = sum(l)
	bonusPts = 2 * sum(l) + len(l)
	reg = 0
	regPts = 0
	if beg:
		bonus -= l[0]
		reg += l[0]
		bonusPts -= 2 * l[0] + 1
		regPts += 2 * l[0]
	if end:
		bonus -= l[len(l) - 1]
		reg += l[len(l) - 1]
		bonusPts -= 2 * l[len(l) - 1] + 1
		regPts += 2 * l[len(l) - 1]
	if k > bonus:
		score += bonusPts
		k -= bonus
		score += 2 * min(reg, k)
	else:
		if beg:
			del l[0]
		if end:
			del l[-1]
		l.sort()
		for i in range(len(l)):
			if k >= l[i]:
				score += 2 * l[i] + 1
				k -= l[i]
			else:
				score += 2 * k
				break
	print(score)


t = int(input())
for qwe in range(t):
	[n, k] = [int(j) for j in input().split()]
	s = input()
	l = list(s)
	c = 0
	a = []
	if l[0] == 'W':
		ans = 1
	else:
		ans = 0
	for i in range(1, n):
		if l[i] == 'W':
			if l[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	m = -1
	fl = []
	for i in range(n):
		if l[i] == 'W':
			if m == 0 and c > 0:
				a.append(c)
			elif c > 0:
				fl.append(c)
			c = 0
			m = 0
		else:
			c += 1
	fl.append(c)
	a.sort()
	for j in a:
		if k >= j:
			ans += 2 * j + 1
			k -= j
		else:
			ans += 2 * k
			k = 0
	if ans == 0:
		ans = max(2 * k - 1, 0)
	else:
		ans += 2 * min(sum(fl), k)
	print(ans)


import sys, os
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
MOD = 998244353

def main():
	ans = []
	for _ in range(int(input())):
		(n, k) = read()
		t = input().strip()
		s = 'Z' + t + 'Z'
		s = s.split('W')
		s.sort()
		score = 0
		for i in range(n):
			if t[i] == 'W':
				if i > 0 and t[i - 1] == 'W':
					score += 2
				else:
					score += 1
		if k == 0:
			ans.append(str(score))
			continue
		for i in s:
			if not i:
				continue
			if i == 'Z':
				continue
			if i[0] == 'Z' and i[-1] == 'Z':
				score += 2 * min(k, len(i) - 2) - 1
				k -= min(k, len(i) - 2)
			elif not (i[0] == 'Z' or i[-1] == 'Z'):
				score += 2 * min(k, len(i)) + [0, 1][k >= len(i)]
				k -= min(k, len(i))
			else:
				score += 2 * min(k, len(i) - 1)
				k -= min(k, len(i) - 1)
			if k == 0:
				break
		ans.append(str(score))
	print('\n'.join(ans))
main()


import sys
input = lambda : sys.stdin.readline().strip()
for i in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(input())
	ans = [0]
	lol = [0]
	lk = 0
	if len(a) == 1:
		if a[0] == 'W':
			print(1)
		elif k:
			print(1)
		else:
			print(0)
		continue
	for i in range(n):
		if a[i] == 'W':
			if lol[-1] != 0:
				lol.append(0)
				lk = 1
			if ans[-1] == 0:
				ans.append(1)
			else:
				ans.append(2)
		else:
			ans.append(0)
			lol[-1] += 1
	if lol[-1] == 0:
		del lol[-1]
	answ = sum(ans)
	lox = []
	if len(lol) > 1:
		lox = lol[1:-1]
	popa = 0
	if len(lol) == 0:
		print(answ)
		continue
	if a[0] == 'W' and lk:
		lox.append(lol[0])
	else:
		popa = lol[0]
	if len(lol) == 1:
		pass
	elif a[-1] == 'W' and lk:
		lox.append(lol[-1])
	else:
		popa += lol[-1]
	lox.sort()
	l = len(lox)
	for i in range(len(lox)):
		if k >= lox[i]:
			k -= lox[i]
			answ += 2 * lox[i] + 1
		else:
			answ += 2 * k
			k = 0
	k = min(k, popa)
	if 'W' in a:
		answ += 2 * k
		print(answ)
	else:
		answ += max(0, 2 * k - 1)
		print(answ)


import os
import sys
from io import BytesIO, IOBase
from functools import cmp_to_key

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split(' '))
		a = list(input())
		start = -1
		end = -1
		temp = []
		for x in range(n):
			if a[x] == 'L':
				end += 1
			else:
				if start != end:
					temp.append([end - start, [start + 1, end]])
				start = x
				end = x
		if start != end:
			temp.append([end - start, [start + 1, end]])

		def boss(a, b):
			if a[1][0] == 0 or a[1][1] == n - 1:
				if b[1][0] == 0 or b[1][1] == n - 1:
					if a[0] > b[0]:
						return 1
					else:
						return -1
				else:
					return 1
			elif b[1][0] == 0 or b[1][1] == n - 1:
				if a[1][0] == 0 or a[1][1] == n - 1:
					if a[0] > b[0]:
						return 1
					else:
						return -1
				else:
					return -1
			elif a[0] > b[0]:
				return 1
			else:
				return -1
		temp.sort(key=cmp_to_key(boss))
		for x in temp:
			if k <= 0:
				break
			if x[1][1] == n - 1:
				for z in range(x[1][0], x[1][1] + 1):
					a[z] = 'W'
					k -= 1
					if k <= 0:
						break
			else:
				for z in range(x[1][1], x[1][0] - 1, -1):
					a[z] = 'W'
					k -= 1
					if k <= 0:
						break
			if k <= 0:
				break
		ans = 0
		chk = -1
		for x in range(n):
			if a[x] == 'W':
				if chk == -1:
					ans += 1
					chk = 0
				else:
					ans += 2
			else:
				chk = -1
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def main():
	(n, k) = map(int, input().split())
	line = input()
	was = False
	prev = False
	res = 0
	before = 0
	spare_sizes = []
	sz = 0
	for i in line:
		if not was:
			if i == 'L':
				before += 1
			else:
				was = True
		if was:
			if i == 'L':
				sz += 1
			elif sz > 0:
				spare_sizes.append(sz)
				sz = 0
		if i == 'W':
			if prev:
				res += 2
			else:
				res += 1
			prev = True
		else:
			prev = False
	if was:
		before += sz
	if res == 0 and k > 0:
		res -= 1
	spare_sizes = sorted(spare_sizes)
	for i in range(len(spare_sizes)):
		if spare_sizes[i] > k:
			res += 2 * k
			k = 0
			break
		else:
			res += 2 * spare_sizes[i]
			k -= spare_sizes[i]
			res += 1
		if k == 0:
			break
	res += 2 * min(k, before)
	print(res)
t = int(input())
for i in range(t):
	main()


import random

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	a = []
	for i in s:
		if i == 'L':
			a.append(0)
		else:
			a.append(1)
	for i in range(n):
		if i != 0 and i != n - 1:
			if a[i - 1] == 1 and a[i + 1] == 1 and (a[i] == 0) and (k > 0):
				k -= 1
				a[i] = 1
	c = 0
	l = -1
	f = []
	edge = []
	for i in range(n):
		if a[i] == 0 and l == -1:
			l = i
		elif a[i] == 1 and l != -1:
			if l == 0:
				edge.append([i - l, [l, i - 1]])
			else:
				f.append([i - l, [l, i - 1]])
			l = -1
	if l != -1:
		edge.append([n - l, [l, n - 1]])
	f.sort()
	edge.sort()
	i = 0
	while k > 0 and i < len(f):
		for j in range(f[i][1][0], f[i][1][1] + 1):
			a[j] = 1
			k -= 1
			if k == 0:
				break
		i += 1
	i = 0
	while k > 0 and i < len(edge):
		if edge[i][1][0] == 0:
			for j in range(edge[i][1][1], edge[i][1][0] - 1, -1):
				a[j] = 1
				k -= 1
				if k == 0:
					break
		else:
			for j in range(edge[i][1][0], edge[i][1][1] + 1):
				a[j] = 1
				k -= 1
				if k == 0:
					break
		i += 1
	ans = 0
	for i in range(n):
		if a[i] == 1:
			if i == 0:
				ans += 1
			elif a[i - 1] == 1:
				ans += 2
			else:
				ans += 1
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(input())
	l = []
	prev = 0
	c = 0
	f = 0
	for i in range(n):
		if s[i] == 'L':
			if f == 0:
				ind = i
				f = 1
			prev = i
			c += 1
		else:
			if c != 0:
				l.append([c, ind, prev])
			c = 0
			f = 0
	if c != 0:
		l.append([c, ind, prev])
	if s.count('L') <= k:
		print(2 * n - 1)
	elif s.count('L') == n:
		print(max(2 * k - 1, 0))
	else:
		l.sort(key=lambda x: x[0])
		for i in range(len(l)):
			if l[i][1] == 0 or l[i][-1] == n - 1:
				continue
			for j in range(l[i][1], l[i][-1] + 1):
				if k == 0:
					break
				s[j] = 'W'
				k = k - 1
			if k == 0:
				break
		ans = 0
		f = 0
		for i in range(n):
			if s[i] == 'L':
				f = 0
			elif f == 0:
				ans += 1
				f = 1
			else:
				ans += 2
		if k == 0:
			print(ans)
		else:
			print(ans + k * 2)


def getsum(result):
	answer = 0
	box = []
	count = 0
	for i in result:
		if i == 'W':
			count += 1
		else:
			box.append(count)
			count = 0
	box.append(count)
	for i in box:
		if i != 0:
			answer += 2 * i - 1
	return answer
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	result = input()
	wcount = result.count('W')
	if wcount == 0:
		if k != 0:
			print(2 * k - 1)
		else:
			print(0)
	else:
		score = getsum(result)
		betL = []
		nobetL = []
		start = -1
		end = -1
		tempw = 0
		count = 0
		for i in range(len(result)):
			if result[i] == 'L':
				count += 1
			else:
				tempw += 1
				if start == -1 and end == -1:
					if count != 0:
						nobetL.append(count)
					count = 0
					start = i
				elif start != -1 and end == -1 and (tempw != wcount):
					if count != 0:
						betL.append(count)
					count = 0
				elif start != -1 and end == -1 and (tempw == wcount):
					if count != 0:
						betL.append(count)
					count = 0
					end = i
		if count != 0:
			nobetL.append(count)
		betL = sorted(betL)
		nobetL = sorted(nobetL)
		tempsum = 0
		if sum(betL) >= k:
			for i in betL:
				if k >= i:
					tempsum += 2 * i + 1
					k -= i
				else:
					tempsum += 2 * k
					break
			print(score + tempsum)
		else:
			for i in betL:
				if k >= i:
					tempsum += 2 * i + 1
					k -= i
				else:
					tempsum += 2 * k
					break
			for i in nobetL:
				if k >= i:
					tempsum += 2 * i
					k -= i
				else:
					tempsum += 2 * k
					break
			print(score + tempsum)


t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	S = input()
	consL0 = []
	consL1 = []
	consL2 = []
	startW = S[0] == 'W'
	c = 1 if S[0] == 'L' else 0
	ans = 1 if S[0] == 'W' else 0
	for i in range(1, n):
		if S[i] == 'L':
			c += 1
		else:
			if c > 0:
				if startW:
					consL0.append(c)
				else:
					consL1.append(c)
				c = 0
			startW = True
			ans += 1 if S[i - 1] == 'L' else 2
	if c > 0:
		if startW:
			consL1.append(c)
		else:
			consL2.append(c)
	if k > 0:
		consL0.sort()
		while len(consL0) > 0 and k > 0:
			l = consL0.pop(0)
			if k >= l:
				ans += 2 * l + 1
				k -= l
			else:
				ans += 2 * k
				k = 0
				break
	if k > 0:
		consL1.sort()
		while len(consL1) > 0 and k > 0:
			l = consL1.pop(0)
			ans += 2 * min(k, l)
			k -= min(k, l)
	if k > 0 and len(consL2) > 0:
		l = consL2[0]
		ans += 2 * min(k, l) - 1
	print(ans)


import sys
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	string = input().strip()
	if 'W' not in string:
		ans = min(n, k) * 2 - 1
		print(max(ans, 0))
		return
	L_s = []
	cnt = 0
	bef = string[0]
	ans = 0
	for s in string:
		if s == bef:
			cnt += 1
		else:
			if bef == 'L':
				L_s.append(cnt)
			else:
				ans += cnt * 2 - 1
			cnt = 1
		bef = s
	if bef == 'W':
		ans += cnt * 2 - 1
		cnt = 0
	if string[0] == 'L' and L_s:
		cnt += L_s[0]
		L_s = L_s[1:]
	L_s.sort()
	for l in L_s:
		if k >= l:
			ans += l * 2 + 1
			k -= l
		else:
			ans += k * 2
			k = 0
	ans += 2 * min(k, cnt)
	print(ans)
for _ in range(int(input())):
	main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	s = [s[i] for i in range(n)]
	base = s.count('W')
	if base == 0:
		if k:
			print(2 * k - 1)
		else:
			print(0)
	elif base + k >= n:
		print(2 * n - 1)
	else:
		interval = []
		while s and s[-1] == 'L':
			s.pop()
		s = s[::-1]
		while s and s[-1] == 'L':
			s.pop()
		while s:
			if s[-1] == 'W':
				while s and s[-1] == 'W':
					s.pop()
			else:
				tmp = 0
				while s and s[-1] == 'L':
					s.pop()
					tmp += 1
				interval.append(tmp)
		interval.sort(reverse=True)
		K = k
		while interval and k:
			if k >= interval[-1]:
				k -= interval.pop()
			else:
				break
		print(2 * (base + K) - 1 - len(interval))


t = int(input())
for _ in range(t):
	(n, K) = map(int, input().split())
	s = input()
	n = len(s)

	def way1():
		global n, K, s
		if s.find('W') == -1:
			return max(0, 2 * min(K, n) - 1)
		k = K
		score = int(s[0] == 'W')
		for i in range(1, n):
			if s[i - 1] == s[i] == 'W':
				score += 2
			elif s[i] == 'W':
				score += 1
		loss_streaks = [len(x) for x in s.split('W') if x != '']
		if s[0] == 'L':
			first = loss_streaks[0]
			del loss_streaks[0]
		else:
			first = 0
		if s[-1] == 'L' and loss_streaks:
			last = loss_streaks[-1]
			del loss_streaks[-1]
		else:
			last = 0
		loss_streaks.sort()
		for i in range(len(loss_streaks)):
			if loss_streaks[i] <= k:
				k -= loss_streaks[i]
				score += loss_streaks[i] * 2 + 1
				loss_streaks[i] = 0
		left = sum(loss_streaks)
		score += 2 * min(left, k)
		k -= min(left, k)
		if k and last:
			score += 2 * min(last, k)
			k -= min(last, k)
		if k and first:
			score += 2 * min(first, k)
		return score
	print(way1())


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	(ans, t, b, f) = (0, 0, 0, 0)
	l = []
	for i in range(n):
		if s[i] == 'W':
			ans += f + 1
			f = 1
			if b:
				l.append(b)
			b = 0
		else:
			f = 0
			b += 1
	if b:
		l.append(b)
	(m, v) = (0, 0)
	if s[0] == 'L':
		m = l.pop(0)
	if s[-1] == 'L':
		if ans:
			v = l.pop()
	l.sort()
	while k and l:
		t = l.pop(0)
		if k >= t:
			ans += t * 2 + 1
			k -= t
		else:
			ans += 2 * k
			k = 0
	if k:
		ans = ans + 2 * min(k, m + v) if ans else ans + 2 * min(k, m) - 1
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	streaks = []
	firstwin = -1
	for i in range(n):
		if s[i] == 'W':
			firstwin = i
			break
	if firstwin == -1:
		print(max(0, min(2 * n - 1, 2 * k - 1)))
		continue
	ans = 0
	curr = 0
	for i in range(firstwin, n):
		if s[i] == 'W':
			if i > 0 and s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
			if curr > 0:
				streaks.append(curr)
				curr = 0
		else:
			curr += 1
	streaks.sort()
	m = len(streaks)
	pointer = -1
	while pointer + 1 < m and k >= streaks[pointer + 1]:
		ans += streaks[pointer + 1] * 2 + 1
		k -= streaks[pointer + 1]
		pointer += 1
	ans += 2 * k
	print(min(ans, 2 * n - 1))


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	s = list(input())
	startGroup = []
	endGroup = []
	LGroups = []
	currLGroup = []
	isStart = False
	isEnd = False
	for i in range(n):
		if i == 0:
			isStart = True
		if s[i] == 'W':
			if len(currLGroup) > 0:
				if isStart:
					startGroup = currLGroup
				else:
					LGroups.append(currLGroup)
			isStart = False
			currLGroup = []
		else:
			currLGroup.append(i)
	if len(currLGroup) > 0:
		endGroup = currLGroup
	finalLCount = max(s.count('L') - k, 0)
	s2 = ['W'] * n
	if finalLCount > 0:
		for i in startGroup:
			s2[i] = 'L'
			finalLCount -= 1
			if finalLCount == 0:
				break
	if finalLCount > 0:
		for j in range(len(endGroup) - 1, -1, -1):
			s2[endGroup[j]] = 'L'
			finalLCount -= 1
			if finalLCount == 0:
				break
	if finalLCount > 0:
		LGroups.sort(key=lambda x: len(x), reverse=True)
		for g in LGroups:
			for i in g:
				s2[i] = 'L'
				finalLCount -= 1
				if finalLCount == 0:
					break
			if finalLCount == 0:
				break
	ans = 0
	for i in range(n):
		if s2[i] == 'W':
			ans += 1
			if i > 0 and s2[i - 1] == 'W':
				ans += 1
	print(ans)


def score(s):
	rv = 0
	for z in range(len(s)):
		if s[z] == 'W':
			if z == 0:
				rv += 1
			elif s[z - 1] == 'W':
				rv += 2
			else:
				rv += 1
	return rv
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(input())
	cl = s.count('L')
	if k == 0:
		print(score(s))
	elif k >= cl:
		print((n - 1) * 2 + 1)
	elif cl == n:
		print((k - 1) * 2 + 1)
	else:
		iidx = -1
		eidx = -1
		for z in range(n):
			if s[z] == 'W':
				iidx = z
				break
		for z in range(n - 1, -1, -1):
			if s[z] == 'W':
				eidx = z
				break
		if iidx == eidx:
			print(k * 2 + 1)
		else:
			count = 0
			ans = []
			for z in range(iidx, eidx + 1):
				if s[z] == 'L':
					count += 1
				elif count:
					ans.append((count, z - count))
					count = 0
			if count:
				ans.append((count, eidx + 1 - count))
			ans.sort()
			for z in ans:
				if not k:
					break
				mini = min(k, z[0])
				k -= mini
				for x in range(mini):
					s[x + z[1]] = 'W'
			while k and eidx + 1 < n:
				s[eidx + 1] = 'W'
				eidx += 1
				k -= 1
			while k and iidx - 1 > -1:
				s[iidx - 1] = 'W'
				iidx -= 1
				k -= 1
			print(score(s))


def countStr(string, str_len):
	(l_len, l_sum) = (0, 0)
	(sw_idx, ew_idx) = (-1, -1)
	l_count = {}
	(l_flag, sw_flag) = (False, False)
	for i in range(str_len):
		s = string[i]
		if sw_flag and s == 'L':
			l_flag = True
			l_len += 1
		elif s == 'W':
			if l_flag:
				l_sum += l_len
				l_count[l_len] = l_count.get(l_len, 0) + 1
				l_len = 0
				l_flag = False
			if not sw_flag:
				sw_flag = True
				sw_idx = i
			ew_idx = i
	return (l_sum, l_count, sw_idx, ew_idx)

def reslove(wl_str, n, k):
	(l_sum, l_count, sw_idx, ew_idx) = countStr(wl_str, n)
	L_left_len = sw_idx
	L_right_len = n - ew_idx - 1
	L_all_len = L_left_len + l_sum + L_right_len
	if sw_idx < 0:
		if k == 0 or n == 0:
			return 0
		w = k if n > k else n
		return 2 * w - 1
	if L_all_len <= k:
		return 2 * n - 1
	if l_sum < k:
		w = n - L_all_len + k
		return 2 * w - 1
	lens = list(l_count.keys())
	lens.sort()
	w = n - L_all_len
	bp = sum(l_count.values()) + 1
	for len in lens:
		len_ct = l_count[len]
		l_ct = len * len_ct
		if l_ct <= k:
			bp -= len_ct
			w += l_ct
			k -= l_ct
		else:
			filled = k // len
			bp -= filled
			w += k
			break
	return w * 2 - bp
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	wl_str = input()
	print(reslove(wl_str, n, k))


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf
from itertools import permutations
from copy import deepcopy
from sys import setrecursionlimit

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		a = list(input().rstrip())
		b = []
		i = 0
		while i < n:
			if a[i] == 'L':
				j = i + 1
				while j < n and a[j] == 'L':
					j += 1
				b.append([i, j - 1])
				i = j
			i += 1
		b.sort(key=lambda x: x[1] - x[0] + (0 if x[0] != 0 and x[1] != n - 1 else 10 ** 5))
		for i in range(len(b)):
			for j in range(b[i][0] if b[i][0] != 0 else b[i][1], b[i][1] + 1 if b[i][0] != 0 else b[i][0] - 1, 1 if b[i][0] != 0 else -1):
				if k == 0:
					break
				a[j] = 'W'
				k -= 1
			if k == 0:
				break
		ans = int(a[0] == 'W')
		for i in range(1, n):
			if a[i - 1] == 'W' and a[i] == 'W':
				ans += 2
			elif a[i] == 'W':
				ans += 1
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
import math
from collections import defaultdict, Counter
import operator
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	c = 0
	l = []
	ans = 0
	for j in range(n):
		if s[j] == 'W':
			if j == 0 or s[j - 1] == 'L':
				ans += 1
			else:
				ans += 2
	start = -1
	for j in range(n):
		if s[j] == 'L':
			c += 1
			if start == -1:
				start = j
		elif c > 0:
			if start == 0:
				l.append([c, 1])
			else:
				l.append([c, 0])
			c = 0
			start = -1
	if c > 0:
		if start == 0:
			l.append([c, 2])
		else:
			l.append([c, 1])
	l.sort(key=operator.itemgetter(1, 0))
	for j in l:
		if j[0] <= k:
			if j[1] == 0:
				ans += 2 * j[0] + 1
			elif j[1] == 1:
				ans += 2 * j[0]
			else:
				ans += 2 * j[0] - 1
			k -= j[0]
		else:
			if j[1] == 2:
				ans += max(0, 2 * k - 1)
			else:
				ans += 2 * k
			break
	print(ans)


import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import time
start_time = time.time()
import collections as col
import math
from functools import reduce

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def solve():
	(N, K) = getInts()
	S = listStr()
	if N == 1:
		if K == 1 or S[0] == 'W':
			return 1
		return 0
	gaps = []
	curr = 0
	wins = 0
	for j in range(N):
		if S[j] == 'L':
			curr += 1
		elif curr > 0:
			gaps.append(curr)
			curr = 0
		if S[j] == 'W':
			wins += 1
			if j > 0 and S[j - 1] == 'W':
				wins += 1
	if K == 0:
		return wins
	if S[j] == 'L':
		gaps.append(curr)
	pref = 0
	suff = 0
	if not gaps:
		return wins
	if len(gaps) == 1:
		if S[0] == 'W' and S[-1] == 'W':
			pass
		else:
			if S[0] == 'W' or S[-1] == 'W':
				change = min(K, gaps[0])
				wins += 2 * change
				return wins
			return 2 * K - 1
	if S[0] == 'L':
		pref = gaps[0]
		gaps = gaps[1:]
	if S[-1] == 'L':
		suff = gaps[-1]
		gaps = gaps[:-1]
	gaps.sort(reverse=True)
	while K and gaps:
		x = gaps.pop()
		change = min(K, x)
		if change < x:
			wins += 2 * change
		else:
			wins += 2 * change + 1
		K -= change
	if K:
		change = min(K, pref + suff)
		wins += 2 * change
		K -= change
	return wins
for _ in range(getInt()):
	print(solve())


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = str(input())
	cw = 0
	cnt = 0
	lcount = -1
	llen = dict()
	for i in range(n):
		if i == 0 and s[i] == 'W':
			cnt += 1
			lcount = 0
			cw += 1
		elif s[i] == 'W':
			if s[i - 1] == 'W':
				cnt += 2
			else:
				cnt += 1
			cw += 1
			if lcount > 0:
				if lcount not in llen.keys():
					llen[lcount] = 0
				llen[lcount] += 1
				lcount = 0
			elif lcount < 0:
				lcount = 0
		elif lcount >= 0:
			lcount += 1
	cl = n - cw
	if k == 0:
		print(cnt)
	else:
		lens = []
		for e in llen.keys():
			lens.append(e)
		lens.sort()
		delta = 0
		for l in lens:
			if k < l:
				break
			count = min(k // l, llen[l])
			delta += count * (l * 2 + 1)
			k -= count * l
			cl -= count * l
		if k > 0:
			if k <= cl:
				if cnt == 0:
					delta += (k - 1) * 2 + 1
				else:
					delta += k * 2
			else:
				delta += cl * 2
		print(cnt + delta)


T = int(input())
for _ in range(0, T):
	(n, k) = map(int, input().split())
	L = input()
	s = []
	for i in range(0, len(L)):
		s.append(L[i])
	ptr = len(s)
	for i in range(0, len(s)):
		if s[i] == 'W':
			ptr = i
			break
	dp = []
	c = 0
	st = ptr
	for i in range(ptr + 1, len(s)):
		if s[i] == 'W':
			if c > 0:
				dp.append([c, st + 1, i])
			st = i
			c = 0
		else:
			c += 1
	dp.sort()
	fnl = []
	for i in range(0, len(dp)):
		cnt = dp[i][0]
		j1 = dp[i][1]
		j2 = dp[i][2]
		for j in range(j1, j2):
			fnl.append(j)
	for i in range(st + 1, len(s)):
		fnl.append(i)
	for i in range(ptr - 1, -1, -1):
		fnl.append(i)
	for i in range(0, min(k, len(fnl))):
		s[fnl[i]] = 'W'
	ans = 0
	prev = 0
	for i in range(0, len(s)):
		if s[i] == 'W':
			if prev == 1:
				ans += 2
			else:
				ans += 1
			prev = 1
		else:
			prev = 0
	print(ans)


def calc(p, n):
	score = p[0]
	for i in range(1, n):
		if p[i] and p[i - 1]:
			score += 2
		elif p[i]:
			score += 1
	return score
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	p = [1 if i == 'W' else 0 for i in input()]
	if all((i == 0 for i in p)):
		if k >= n:
			print(max(2 * n - 1, 0))
		else:
			print(max(0, 2 * k - 1))
		continue
	if k == 0:
		print(calc(p, n))
		continue
	(ord, cs) = ([], [])
	ans = 0
	i = 0
	while i < n:
		(l, r) = (i, i)
		if p[i]:
			while r + 1 < n and p[r + 1]:
				r += 1
			ans += (r - l) * 2 + 1
			i = r + 1
			continue
		while r + 1 < n and p[r + 1] == 0:
			r += 1
		if l != 0 and r != n - 1:
			ord.append(r - l + 1)
		else:
			cs.append(r - l + 1)
		i = r + 1
	ord.sort()
	cs.sort()
	ok = True
	for i in ord:
		if k == 0:
			print(ans)
			ok = False
			break
		if k >= i:
			ans += 2 * i + 1
			k -= i
		else:
			ans += 2 * k
			print(ans)
			ok = False
			break
	if not ok:
		continue
	for i in cs:
		if k == 0:
			print(ans)
			ok = False
			break
		if k >= i:
			ans += 2 * i
			k -= i
		else:
			ans += 2 * k
			print(ans)
			ok = False
			break
	if not ok:
		continue
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = list(input())
	ind = []
	p = -1
	if arr[0] == 'W':
		p = 0
	for i in range(1, n):
		if arr[i] == 'W' and arr[i - 1] == 'L':
			if p != -1:
				ind.append([i - p - 1, [p, i]])
				p = i
			else:
				p = i
		elif arr[i] == arr[i - 1] == 'W':
			p = i
	ind.sort()
	for i in ind:
		if k == 0:
			break
		else:
			for j in range(i[1][0] + 1, i[1][1]):
				if k:
					arr[j] = 'W'
					k -= 1
				else:
					break
	if k:
		if arr[0] != 'W':
			if 'W' in arr:
				for i in range(arr.index('W') - 1, -1, -1):
					if k:
						arr[i] = 'W'
						k -= 1
					else:
						break
	if k:
		if arr[-1] != 'W':
			x = n
			for i in range(n - 1, -1, -1):
				if arr[i] == 'W':
					x = i
					break
			for i in range(x + 1, n):
				if k:
					arr[i] = 'W'
					k -= 1
				else:
					break
	if k:
		for i in range(n):
			if k:
				arr[i] = 'W'
				k -= 1
			else:
				break
	ans = int(arr[0] == 'W')
	for i in range(1, n):
		if arr[i] == 'W':
			if arr[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	print(ans)


import sys
import math as m

def fi():
	return sys.stdin.readline()
for _ in range(int(fi())):
	(n, k) = map(int, fi().split())
	s = list(fi())
	s.pop()
	p = 0
	q = 0
	flag = 0
	ans = 0
	prev = 'L'
	l = []
	c = 0
	for i in range(n):
		if s[i] == 'W' and prev == 'L':
			ans += 1
			l.append(c)
			c = 0
		elif s[i] == 'W' and prev == 'W':
			ans += 2
		if s[i] == 'L':
			c += 1
		prev = s[i]
	if s[n - 1] != 'W':
		l.append(c)
	p = l.pop(0)
	if len(l) > 0 and s[n - 1] != 'W':
		q = l.pop()
	l.sort()
	for i in range(len(l)):
		if l[i] <= k:
			ans += l[i] * 2 + 1
			k -= l[i]
		else:
			ans += k * 2
			k = 0
			break
	if p == n and k >= n:
		ans = 2 * p - 1
	elif p == n and k < n:
		ans = max(k * 2 - 1, 0)
	else:
		ans += min(k, p + q) * 2
	print(ans)


from functools import lru_cache

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
t = inp()
for _ in range(t):
	(n, k) = inlt()
	s = insr()
	if k > 0:
		l_groups = []
		i = 0
		while i < n:
			group = []
			while i < n and s[i] == 'L':
				group.append(i)
				i += 1
			if group:
				l_groups.append(group)
			i += 1
		(start, end) = ([], [])
		if l_groups and l_groups[0][0] == 0:
			start = l_groups.pop(0)
		if l_groups and l_groups[-1][-1] == n - 1:
			end = l_groups.pop()
		l_groups.sort(key=lambda a: len(a))
		for group in l_groups:
			for i in group:
				s[i] = 'W'
				k -= 1
				if k == 0:
					break
			if k == 0:
				break
		rem = start[::-1] + end
		for i in range(min(k, len(rem))):
			s[rem[i]] = 'W'
	score = 0
	for (i, ch) in enumerate(s):
		if ch == 'W':
			score += 1
			if i > 0 and s[i - 1] == 'W':
				score += 1
	print(score)


from collections import *
from math import *
M = 10 ** 9 + 7
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	s = list(s)
	mp = []
	cntL = 0
	res = 0
	for ch in s:
		if ch == 'L':
			cntL += 1
	if cntL <= k:
		res = 1 + (n - 1) * 2
	else:
		cnt = 0
		f = 0
		for i in range(n):
			if s[i] == 'L':
				cnt += 1
			else:
				if cnt and f:
					mp.append([cnt, i - cnt])
				f = 1
				cnt = 0
		mp.sort()
		for p in mp:
			for i in range(p[0] + p[1] - 1, p[1] - 1, -1):
				if not k:
					break
				s[i] = 'W'
				k -= 1
		if k:
			f = 0
			for i in range(n):
				if s[i] == 'L' and f:
					s[i] = 'W'
					k -= 1
				elif s[i] == 'W':
					f = 1
				if not k:
					break
		if k:
			for i in range(n - 1, 0, -1):
				if s[i] == 'L':
					s[i] = 'W'
					k -= 1
				if not k:
					break
		if s[0] == 'W':
			res += 1
		for i in range(1, n):
			if s[i] == 'W':
				if s[i - 1] == 'W':
					res += 2
				else:
					res += 1
	print(res)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 30, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(input())
	last = -1
	diff = []
	cou = 0
	cur = 0
	ans = 0
	for i in range(n):
		if s[i] == 'W':
			ans += 1
			if i > 0 and s[i - 1] == 'W':
				ans += 1
			if last != -1:
				if cur != 0:
					diff.append(cur)
			cur = 0
			last = i
		else:
			cou += 1
			cur += 1
	k = min(cou, k)
	diff.sort()
	for i in range(len(diff)):
		if k >= diff[i]:
			ans += diff[i] * 2 + 1
			k -= diff[i]
		else:
			break
	ans += k * 2
	if cou == n and k > 0:
		ans -= 1
	print(ans)


import sys
import math
from decimal import *

def I():
	return int(sys.stdin.readline())

def IL():
	return list(map(int, sys.stdin.readline().strip().split()))

def ILS():
	return list(map(str, sys.stdin.readline().strip().split()))

def solve():
	tt = I()
	for ii in range(tt):
		(n, k) = IL()
		ss = input()
		s = [x for x in ss]
		w = 0
		l = 0
		for i in range(n):
			if s[i] == 'W':
				w += 1
			else:
				l += 1
		if k >= l:
			print(2 * n - 1)
			continue
		ans = 0
		if s[0] == 'W':
			ans += 1
		for i in range(1, n):
			if s[i] == 'W':
				ans += 1
				if s[i - 1] == 'W':
					ans += 1
		if k == 0:
			print(ans)
			continue
		loss = []
		c = 0
		idx = n
		for i in range(n):
			if s[i] == 'W':
				idx = i
				break
		if idx == n:
			print(k * 2 - 1)
			continue
		for i in range(idx, n):
			if s[i] == 'W' and c > 0:
				loss.append(c)
				c = 0
			elif s[i] == 'L':
				c += 1
		loss.sort()
		m = len(loss)
		for i in range(m):
			if k <= 0:
				break
			if loss[i] > k:
				ans += k * 2
				k = 0
			else:
				ans += loss[i] * 2 + 1
				k -= loss[i]
		if k > 0:
			ans += k * 2
		print(ans)
solve()


t = int(input().replace('\n', ''))
for i in range(t):
	line1 = list(map(int, input().replace('\n', '').split(' ')))
	n = line1[0]
	k = line1[1]
	s = list(input().replace('\n', ''))
	(wins, losses, gap_wins) = (0, 0, 0)
	losses_gaps_len = []
	for i in range(n):
		if s[i] == 'W':
			if i == 0 or s[i - 1] == 'L':
				gap_wins += 1
			wins += 1
		else:
			losses += 1
			if i == 0 or s[i - 1] == 'W':
				losses_gaps_len.append(0)
			losses_gaps_len[-1] += 1
	if k > losses:
		print(2 * n - 1)
		continue
	if wins == 0:
		if k == 0:
			print(0)
		else:
			print(2 * k - 1)
		continue
	inf = float('inf')
	if s[0] == 'L':
		losses_gaps_len[0] = inf
	if s[n - 1] == 'L':
		losses_gaps_len[-1] = inf
	sorted_losses_gaps_len = sorted(losses_gaps_len)
	wins += k
	for i in range(len(sorted_losses_gaps_len)):
		if sorted_losses_gaps_len[i] > k:
			break
		else:
			gap_wins -= 1
			k -= sorted_losses_gaps_len[i]
	print(2 * wins - gap_wins)


import sys
lines = sys.stdin.readlines()
cur_line = -1

def input():
	global lines, cur_line
	cur_line += 1
	return lines[cur_line][:-1]
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	base = 0
	gaps = []
	for i in range(n):
		if s[i] == 'W':
			base += 1 if i == 0 or s[i - 1] == 'L' else 2
		elif s[i] == 'L':
			if i == 0 or s[i - 1] == 'W':
				gaps.append(1)
			else:
				gaps[-1] += 1
	if len(gaps) > 0:
		if s[0] == 'L':
			gaps[0] = 9999999
		if s[-1] == 'L':
			gaps[-1] = 9999999
	gaps.sort()
	c = 0
	su = 0
	for i in gaps:
		su += i
		if su <= k:
			base += 1
	t = sum((1 for c in s if c == 'L'))
	off = 1 if t == n else 0
	print(max(0, base + min(k, t) * 2 - off))


for test in range(int(input())):
	[n, k] = list(map(int, input().split(' ')))
	s = input()
	w = False
	l = 0
	sl = []
	pg = False
	res = 0
	z = 0
	ko = 0
	for r in s:
		if r == 'W':
			if pg:
				res += 2
			else:
				res += 1
			pg = True
			if w:
				sl.append(l)
				l = 0
			else:
				w = True
		elif w:
			l += 1
			pg = False
		else:
			z += 1
	if len(sl) > 0:
		sl.sort()
		c = 0
		j = 0
		while j < len(sl) and c + sl[j] <= k:
			c += sl[j]
			if sl[j] > 0:
				res += sl[j] * 2 + 1
			j += 1
		if j == len(sl):
			res = res + min(k - c, z + l) * 2
		else:
			res = res + (k - c) * 2
	elif w:
		res = res + min(k, z + l) * 2
	elif k > 0:
		res = res + min(k, z) * 2 - 1
	print(res)


from sys import stdin, stdout
import math, sys, heapq
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import random
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		t = []
		(n, k) = In()
		s = input()
		totalL = s.count('L')
		if totalL <= k:
			print(2 * n - 1)
			return
		if n == totalL:
			print(max(2 * k - 1, 0))
			return
		no0 = 0
		now = 0
		ans = 0
		for i in range(n):
			if s[i] == 'W':
				now += 1
				if no0:
					t.append(no0)
					no0 = 0
			else:
				no0 += 1
				if now:
					ans += now * 2 - 1
					now = 0
		(t1, t2) = (0, 0)
		if s[0] == 'L':
			t1 = t.pop(0)
		if s[-1] == 'L':
			t2 = no0
		if now:
			ans += now * 2 - 1
		t.sort()
		for x in t:
			if k >= x:
				k -= x
				ans += 2 * x
				ans += 1
			else:
				ans += 2 * k
				k = 0
				break
		if k:
			if t1 < t2:
				ans += max(min(k, t1) * 2, 0)
				k -= min(k, t1)
				if k:
					ans += max(min(k, t2) * 2, 0)
			else:
				ans += max(min(k, t2) * 2, 0)
				k -= min(k, t2)
				if k:
					ans += max(min(k, t1) * 2, 0)
		print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


import sys
inp = sys.stdin.buffer.readline
inar = lambda : list(map(int, inp().split()))
inin = lambda : int(inp())
inst = lambda : inp().decode().strip()
wrt = sys.stdout.write
pr = lambda *args, end='\n': wrt(' '.join([str(x) for x in args]) + end)
enum = enumerate
inf = float('inf')
cdiv = lambda x, y: -(-x // y)
_T_ = int(input())
for _t_ in range(_T_):
	(n, k) = list(map(int, input().split()))
	s = list(input())
	if k >= s.count('L'):
		print(2 * n - 1)
		continue
	w = 0
	l = 0
	prev = ' '
	val = []
	ans = 0
	for i in s:
		if i == 'W' and prev == 'W':
			ans += 2
		if i == 'W' and prev != 'W':
			ans += 1
		if i != prev:
			if prev == ' ':
				val.append(0)
			elif prev == 'W':
				val.append(2 * w)
				w = 0
			else:
				val.append(2 * l + 1)
				l = 0
		if i == 'W':
			w += 1
		else:
			l += 1
		prev = i
	if w == 0:
		val.append(2 * l + 1)
		val.append(0)
	elif l == 0:
		val.append(2 * w)
	ar = []
	for i in range(len(val) - 2):
		(w1, l, w2) = (val[i], val[i + 1], val[i + 2])
		if w1 % 2 == 0 and l % 2 == 1 and (w2 % 2 == 0):
			ar.append((w1, l, w2))
	tmp = []
	for i in ar:
		if i[0] == 0 or i[2] == 0:
			tmp.append(i)
			ar.remove(i)
	ar.sort(key=lambda x: x[1])
	tmp.sort(key=lambda x: x[0] + x[2])
	ar.extend(tmp)
	ar.reverse()
	while k > 0 and ar:
		(w1, l, w2) = ar.pop()
		w1 //= 2
		l //= 2
		w2 //= 2
		if l <= k:
			if w1 > 0 and w2 > 0:
				ans += 2 * l + 1
			elif w1 == 0 and w2 == 0:
				ans += 2 * l - 1
			else:
				ans += 2 * l
			k -= l
		elif w1 == w2 == 0:
			ans += 2 * k - 1
			k = 0
		else:
			ans += 2 * k
			k = 0
	print(ans)


tests = int(input())
for test in range(tests):
	(n, k) = map(int, input().split())
	s = 'L' + input().strip() + 'L'
	res = 0
	pr = 'L'
	for c in s[1:-1]:
		if c == 'W':
			if pr == 'L':
				res += 1
			else:
				res += 2
		pr = c
	r = 0
	if res == 0:
		r = 1
	a = [len(c) for c in s.split('W')]
	a = list(filter(lambda x: x != 0, a))
	t = len(a)
	for i in range(t):
		if i == 0 or i == t - 1:
			a[i] = 2 * a[i] - 2
		else:
			a[i] = 2 * a[i] + 1
	b = sorted(a[1:-1])
	for i in b:
		if k * 2 + 1 < i:
			res += k * 2
		else:
			res += i
		k -= i // 2
		if k <= 0:
			break
	if k > 0:
		res += min(k * 2, a[0])
		k -= a[0] // 2
	if k > 0:
		res += min(k * 2, a[t - 1])
		k -= a[t - 1] // 2
	if res > 0:
		res -= r
	res = min(res, n * 2 - 1)
	print(res)


from collections import defaultdict
T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	s = input()
	ko = k
	curr = 0
	if s[0] == 'W':
		curr += 1
	gaps = defaultdict(int)
	gap = 0
	for i in range(1, n):
		if s[i] == 'W':
			gaps[gap] += 1
			gap = 0
			curr += 1
			if s[i - 1] == 'W':
				curr += 1
		else:
			gap += 1
	if curr == 0:
		if k != 0:
			curr -= 1
	else:
		fg = s.index('W')
		if fg > 1:
			gaps[fg - 1] -= 1
	gaps_filled = 0
	for (x, y) in sorted(gaps.items()):
		if x == 0:
			continue
		if k // x >= y:
			gaps_filled += y
			k -= y * x
		else:
			gaps_filled += k // x
			break
	ko = min(ko, s.count('L'))
	ans = curr + ko * 2 + gaps_filled
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = input()
	if k == 0:
		c = a.split('L')
		ans = 0
		for i in range(len(c)):
			if len(c[i]) >= 1:
				ans = ans + ((len(c[i]) - 1) * 2 + 1)
		print(ans)
		continue
	c = a.split('W')
	counter = {}
	for i in range(1, len(c) - 1):
		if len(c[i]) > 0:
			zz = len(c[i])
			if zz in counter:
				counter[zz] += 1
			else:
				counter[zz] = 1
	ans = 0
	counter1 = []
	for i in counter:
		counter1.append([i, counter[i]])
	if len(c) == 1:
		print(max((min(len(c[0]), k) - 1) * 2 + 1, 0))
		continue
	counter = counter1
	counter.sort()
	for i in range(len(counter)):
		if counter[i][0] * counter[i][1] <= k:
			k -= counter[i][1] * counter[i][0]
			ans += ((counter[i][0] - 1) * 2 + 3) * counter[i][1]
		else:
			ans1 = k // counter[i][0]
			ans += ((counter[i][0] - 1) * 2 + 3) * ans1
			ans1 = k % counter[i][0]
			k = 0
			ans += ans1 * 2
			break
	ramu = c[0].count('L') + c[-1].count('L')
	h = min(ramu, k)
	ans += h * 2
	c = a.split('L')
	for i in range(len(c)):
		if len(c[i]) >= 1:
			ans = ans + ((len(c[i]) - 1) * 2 + 1)
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	if all((i == 'L' for i in s)):
		print(max(0, 2 * k - 1))
		continue
	f = False
	if s[0] == 'L':
		f = True
	cur = s[0]
	l = []
	cnt = 1
	f2 = True
	score = 0
	for i in range(1, n):
		if cur == s[i]:
			cnt += 1
		else:
			if f2:
				if f:
					l.append((cnt, 2 * cnt))
				else:
					score += cnt * 2 - 1
				f2 = False
			elif cur == 'W':
				score += cnt * 2 - 1
			else:
				l.append((cnt, 2 * cnt + 1))
			cnt = 1
			cur = s[i]
	if s[-1] == 'W':
		score += 2 * cnt - 1
	elif f2:
		l.append((cnt, 2 * cnt - 1))
	else:
		l.append((cnt, cnt * 2))
	l.sort(key=lambda x: x[1] / x[0], reverse=True)
	cnt = s.count('L')
	for (i, j) in l:
		if k - i < 0:
			continue
		else:
			score += j
			k -= i
			cnt -= i
	print(score + 2 * min(k, cnt))


t = int(input())

def binsearch(nums, target):
	left = 0
	right = len(nums) - 1
	while left <= right:
		mid = (left + right) // 2
		if nums[mid] == target:
			return mid
		elif nums[mid] > target:
			right = mid - 1
		elif nums[mid] < target:
			left = mid + 1
	return left
for tc in range(t):
	(n, k) = map(int, input().split())
	s = input()
	if n == 1:
		print(min(1, k + s.count('W')))
		continue
	wins = s.count('W')
	if k >= n - wins:
		print(2 * n - 1)
		continue
	if wins == 0:
		print(max(0, 2 * k - 1))
		continue
	gaps = []
	last = '0'
	winstreaks = 1
	c = 0
	fl = 0
	for i in range(n):
		if s[i] == 'L' and (not fl):
			continue
		if s[i] == 'W' and (not fl):
			fl = 1
		elif s[i] == 'W' and s[i - 1] == 'L' and fl:
			winstreaks += 1
			gaps.append(c)
			c = 0
		elif s[i] == 'L':
			c += 1
	gaps1 = sorted(gaps)
	r = 0
	rc = 0
	while r < len(gaps1):
		if rc + gaps1[r] <= k:
			rc += gaps1[r]
			winstreaks -= 1
			r += 1
		else:
			break
	res = 2 * (k + wins) - winstreaks
	print(res)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for j in range(int(input())):
	(n, k) = map(int, input().split())
	vals = [k for k in input()]
	init = 0
	for s in range(n):
		if vals[s] == 'W':
			if s > 0 and vals[s - 1] == 'W':
				init += 2
			else:
				init += 1
	ans = []
	chain = []
	storef = []
	storel = []
	for s in range(n):
		if vals[s] == 'L':
			chain.append(s)
		else:
			if len(chain) > 0:
				if chain[0] == 0:
					storef = chain.copy()
				elif chain[-1] == n - 1:
					storel = chain.copy()
				else:
					ans.append((len(chain), chain.copy()))
			chain.clear()
	if len(chain) > 0:
		if chain[0] == 0:
			storef = chain.copy()
		elif chain[-1] == n - 1:
			storel = chain.copy()
		else:
			ans.append((len(chain), chain.copy()))
	ans.sort(key=lambda x: x[0], reverse=True)
	while k > 0 and len(ans) > 0:
		v0 = ans.pop()[1]
		if k >= len(v0):
			k -= len(v0)
			init += 2 * len(v0) + 1
		else:
			init += 2 * k
			k = 0
	if len(storel) > 0 and k > 0:
		if k >= len(storel):
			k -= len(storel)
			init += 2 * len(storel)
		else:
			init += 2 * k
			k = 0
	if len(storef) > 0 and k > 0:
		if k >= len(storef):
			if storef[-1] == n - 1:
				k -= len(storef)
				init += 1 + 2 * (len(storef) - 1)
			else:
				k -= len(storef)
				init += 2 * len(storef)
		elif storef[-1] == n - 1:
			init += 1 + 2 * (k - 1)
			k = 0
		else:
			init += 2 * k
			k = 0
	print(init)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	arr = list(input())
	last = False
	tot = 0
	for i in range(n):
		if arr[i] == 'W':
			if last:
				tot += 2
			else:
				tot += 1
				last = True
		else:
			last = False
	globalFlag = tot > 0
	dists = []
	last = -1
	flag = False
	prefix = 0
	sufix = 0
	for i in range(n):
		if not flag:
			if arr[i] == 'W':
				prefix = i
				last = i
				flag = True
		elif arr[i] == 'W':
			if i - last > 1:
				dists.append(i - last - 1)
			last = i
	sufix = n - last - 1
	if not flag:
		sufix = n
	dists.sort()
	for i in range(len(dists)):
		canAtThis = min(k, dists[i])
		if k == 0:
			break
		if k >= dists[i]:
			tot += 2 * canAtThis + 1
			k -= canAtThis
		else:
			tot += 2 * canAtThis
			k -= canAtThis
		if k == 0:
			break
	if k != 0 and sufix != 0:
		sufixGive = min(k, sufix)
		tot += 1
		tot += sufixGive * 2 - 1
		k -= sufixGive
		if not globalFlag:
			tot -= 1
	if globalFlag:
		if k != 0 and prefix != 0:
			prefixGive = min(k, prefix)
			tot += prefixGive * 2
	print(tot)


import sys, os, io
input = sys.stdin.readline
T = int(input())
ans = [0] * T
for t in range(T):
	(N, K) = map(int, input().split())
	S = input().split()[0]
	ans[t] = 0
	for (i, s) in enumerate(S):
		if i == 0:
			if s == 'W':
				ans[t] += 1
		elif s == 'W':
			ans[t] += 1
			if S[i - 1] == 'W':
				ans[t] += 1
	if 'W' in S:
		ans[t] += min(S.count('L'), K) * 2
	else:
		ans[t] += max(min(S.count('L'), K) * 2 - 1, 0)
	T = S.split('W')
	lis = []
	for r in T[1:-1]:
		if len(r) > 0:
			lis.append(len(r))
	if len(lis):
		lis.sort()
		for l in lis:
			if K >= l:
				ans[t] += 1
				K -= l
print(*ans, sep='\n')


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	s = list(input())
	ans = 0
	for i in range(1, n):
		if s[i] == 'W':
			if s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	if s[0] == 'W':
		ans += 1
	k = min(k, s.count('L'))
	diff = []
	if s.count('L') == n:
		print(max(2 * k - 1, 0))
		continue
	start = 0
	pre = s.index('W')
	start = pre
	for i in range(pre + 1, n):
		if s[i] == 'W':
			if i - pre - 1 != 0:
				diff.append(i - pre - 1)
			pre = i
	diff.sort()
	for i in diff:
		if i <= k:
			ans += 2 * i + 1
			k -= i
		else:
			ans += 2 * k
			k = 0
			break
	if k > 0:
		ans += 2 * k
	print(ans)


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)

def put():
	return map(int, stdin.readline().split())
for _ in range(int(input())):
	(n, k) = put()
	s = input()
	mx = 2 * n - 1
	l = []
	ind = -1
	ans = 0
	if s.count('W') == 0 and k > 0:
		print(2 * k - 1)
	else:
		if s[0] == 'W':
			ans += 1
		for i in range(1, len(s)):
			if s[i] == 'W' and s[i - 1] == 'W':
				ans += 2
			elif s[i] == 'W':
				ans += 1
		for i in range(len(s)):
			if ind == -1 and s[i] == 'W':
				ind = i
			elif s[i] == 'W' and i - ind > 1:
				l.append(i - ind - 1)
				ind = i
			elif s[i] == 'W':
				ind = i
		l.sort()
		ind = 0
		while ind < len(l) and k >= 0:
			if l[ind] <= k:
				ans += 2 * l[ind] + 1
				k -= l[ind]
			else:
				ans += 2 * k
				k = 0
			ind += 1
		if k > 0:
			ans += 2 * k
		print(min(mx, ans))


TC = int(input())
for tc in range(TC):
	(N, K) = map(int, input().split())
	S = list(input())
	w = 0
	l = []
	rw = 0
	rl = 0
	start = 0
	for s in S:
		if s == 'W':
			if rl > 0:
				if w > 0:
					l.append(rl)
				else:
					start = rl
				rl = 0
			if rw > 0:
				rw += 2
			else:
				rw = 1
		else:
			if rw > 0:
				w += rw
				rw = 0
			rl += 1
	if rl > 0:
		start += rl
	if rw > 0:
		w += rw
	l.sort()
	for lc in l:
		if K >= lc:
			w += 2 * lc + 1
			K -= lc
		else:
			w += 2 * K
			K = 0
			break
	if K > start:
		if w > 0:
			w += start * 2
		else:
			w = start * 2 - 1
	elif w > 0:
		w += K * 2
	elif K > 0:
		w = K * 2 - 1
	print(w)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	string = input()
	string = 'LL' + string
	wcount = 0
	lcount = 0
	wlw = []
	pre1 = 'L'
	pre2 = 'L'
	wstart = -100000000000
	for (j, i) in enumerate(string[2:]):
		if i == 'W':
			wcount += 1
			wstart = j - wstart
			if wstart > 1:
				wlw.append(wstart - 1)
			else:
				wcount += 1
			wstart = j
		else:
			lcount += 1
	wlw = wlw[1:]
	wlw.sort()
	result = -1
	if k <= 0:
		result = wcount
	elif lcount <= k:
		result = n * 2 - 1
	else:
		kcopy = k
		val = 0
		for i in wlw:
			if i <= kcopy:
				val += i * 2 + 1
				kcopy -= i
			else:
				break
		val += kcopy * 2
		result = wcount + val
		if wcount == 0:
			result -= 1
	print(result)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = input()
	lc = a.count('L')
	z = []
	curr = 0
	for i in range(n):
		if a[i] == 'L':
			curr += 1
		else:
			if curr > 0:
				z.append(curr)
			curr = 0
	ini = []
	if a[0] == 'L' and len(z) > 0:
		ini.append(z[0])
		z = z[1:]
	if curr > 0:
		ini.append(curr)
	z.sort()
	ini.sort()
	res = 0
	s = 0
	i = 0
	while i < len(z):
		if s + z[i] <= k:
			res += 2 * z[i] + 1
			s += z[i]
		else:
			break
		i += 1
	if s < k and i != len(z):
		res += (k - s) * 2
		s = k
	if s < k and len(ini) > 0:
		if s + ini[0] <= k:
			s += ini[0]
			res += 2 * ini[0]
			if lc == n:
				res -= 1
		else:
			res += (k - s) * 2
			if lc == n:
				res -= 1
			s = k
		if len(ini) > 1:
			if s + ini[1] <= k:
				s += ini[1]
				res += 2 * ini[1]
			else:
				res += (k - s) * 2
				s = k
	if a[0] == 'W':
		res += 1
	for i in range(1, n):
		if a[i] == 'W':
			res += 1
			if a[i - 1] == 'W':
				res += 1
	print(res)


t = int(input())
for _ in range(t):
	(n, K) = map(int, input().split())
	s = input()
	diff = [0] * (n + 1)
	prev = 0
	I = 0
	J = n - 1
	(flag1, flag2) = (True, True)
	for k in range(n):
		if s[k] == 'W':
			I = k
			flag1 = False
			break
	for k in range(n - 1, -1, -1):
		if s[k] == 'W':
			J = k
			flag2 = False
			break
	if flag1 and flag2:
		if K > 0:
			print(2 * K - 1)
		else:
			print(0)
		continue
	prev = I
	for k in range(I, J + 1):
		if s[k] == 'W':
			if k > prev + 1:
				diff[k - prev - 1] += 1
			prev = k
	j = n
	ans = 0
	for i in range(1, n + 1):
		if K < i:
			j = i
			break
		ans += (2 * i + 1) * min(K // i, diff[i])
		temp = diff[i]
		diff[i] = diff[i] - min(K // i, diff[i])
		K = K - i * min(K // i, temp)
	ans += 2 * min(K, I)
	K = K - min(K, I)
	ans += 2 * min(K, n - 1 - J)
	K = K - min(K, n - 1 - J)
	for k in range(1, n + 1):
		if K <= 0:
			break
		if diff[k] != 0:
			ans += 2 * K
			K = 0
	prev = False
	for i in range(n):
		if s[i] == 'W':
			if prev:
				ans += 2
			else:
				ans += 1
			prev = True
			continue
		prev = False
	print(ans)


from sys import stdin
_input = stdin.readline
(_range, _dict, _int, _sorted, _list, _str) = (range, dict, int, sorted, list, str)
from collections import defaultdict

def solution():
	for _ in _range(_int(_input())):
		(n, k) = [_int(i) for i in _input().split()]
		arr = _list(_input().rstrip('\n'))
		d = defaultdict(_int)
		current_win = -1
		ans = 0
		l_lose = 0
		for i in _range(n):
			if current_win == -1 and arr[i] == 'L':
				l_lose += 1
			if arr[i] == 'W' and current_win < 0:
				current_win = i
			elif arr[i] == 'W' and i - current_win > 1:
				d[i - current_win - 1] += 1
				current_win = i
			elif arr[i] == 'W':
				current_win = i
			if i == 0:
				if arr[i] == 'W':
					ans += 1
			elif arr[i - 1] == 'W' and arr[i] == 'W':
				ans += 2
			elif arr[i] == 'W':
				ans += 1
		if current_win == -1:
			if k > 0:
				if k >= l_lose:
					ans += (l_lose - 1) * 2 + 1
				else:
					ans += (k - 1) * 2 + 1
			print(ans)
			continue
		r_lose = 0
		for i in _range(n - 1, -1, -1):
			if arr[i] == 'L':
				r_lose += 1
			else:
				break
		for i in _sorted(d.keys()):
			if k >= d[i] * i:
				ans += d[i] * (i * 2 + 1)
				k -= d[i] * i
			else:
				ans += k // i * (i * 2 + 1)
				ans += k % i * 2
				k = 0
				break
		if k > 0:
			if k >= l_lose:
				ans += l_lose * 2
				k -= l_lose
			else:
				ans += k * 2
				k = 0
		if k > 0:
			if k >= r_lose:
				ans += r_lose * 2
				k -= r_lose
			else:
				ans += k * 2
				k = 0
		print(ans)
solution()


import sys
t = int(input())
for _ in range(t):
	[n, k] = list(map(int, input().split()))
	temp = 0
	for line in sys.stdin:
		s = line
		break
	prev = 'L'
	current = 'L'
	lsum = 0
	tempsum = 0
	losses = []
	startind = 0
	endind = n - 1
	while startind != n and s[startind] == 'L':
		startind += 1
	while endind != -1 and s[endind] == 'L':
		endind -= 1
	for i in range(startind, endind + 1):
		current = s[i]
		if current == 'L' and prev == 'L':
			lsum += 1
			tempsum += 1
		elif current == 'L' and prev == 'W':
			tempsum = 1
			lsum += 1
		elif current == 'W' and prev == 'L':
			if i != startind:
				losses.append(tempsum)
		prev = current
	losses.sort()
	startloss = startind
	endloss = n - 1 - endind
	lsum += startloss + endloss
	starts = len(losses) + 1
	losses.append(startloss)
	losses.append(endloss)
	if startind == n:
		print(max(2 * k - 1, k))
	else:
		ind = 0
		remk = k
		while ind < len(losses) and remk > 0:
			if remk >= losses[ind]:
				remk -= losses[ind]
				lsum -= losses[ind]
				if ind < len(losses) - 2:
					starts -= 1
			else:
				lsum -= remk
				break
			ind += 1
		print((n - lsum) * 2 - starts)


for t in range(int(input())):
	(n, k) = list(map(int, input().split(' ')))
	s = input()
	point = j = 0
	flag = True
	cnt = 0
	c = []
	j = 0
	while j < n and s[j] == 'L':
		j += 1
	st = j
	if st == n and k > 0:
		print(min(st, k) * 2 - 1)
		continue
	while j < n:
		if flag and s[j] == 'W':
			if cnt > 0:
				c.append(cnt)
			point += 1
			flag = False
			cnt = 0
		elif s[j] == 'W':
			point += 2
		else:
			flag = True
			cnt += 1
		j += 1
	c.sort()
	lst = cnt
	for i in c:
		if k > 0 and k - i >= 0:
			point += 2 * i + 1
			k -= i
		elif k > 0 and k - i < 0:
			point += k * 2
			k = 0
			break
		else:
			k = 0
			break
	if k > 0 and lst >= k:
		point += k * 2
		k = 0
	elif k > 0 and lst < k:
		point += lst * 2
		k -= lst
	if k > 0 and st >= k:
		point += k * 2
		k = 0
	elif k > 0 and st < k:
		point += st * 2
		k -= st
	print(point)


def reverse(li, i, k):
	i -= 1
	t = 0
	while k > 0 and i >= 0:
		if li[i] == 'L':
			li[i] = 'W'
			t += 1
		else:
			return t
		i -= 1
		k -= 1
	return t

def process():
	(n, k) = list(map(int, input().split()))
	li = list(input())
	if n == 1 and k == 1:
		print(1)
		return
	if n == 1 and k == 0:
		if li[0] == 'W':
			print(1)
		else:
			print(0)
		return
	last_win = 0 if li[0] == 'W' else -1
	flag = 1 if li[0] == 'W' else 0
	between_wins = []
	for i in range(1, n):
		if flag == 1 and li[i] == 'W':
			last_win += 1
		elif li[i] == 'L':
			flag = 0
		elif li[i] == 'W':
			flag = 1
			if last_win != -1:
				between_wins.append((last_win + 1, i - 1))
			last_win = i
	between_wins.sort(key=lambda x: x[1] - x[0] + 1)
	temp = []
	if li[0] == 'L':
		ans = 0
		flag = 0
		for i in range(n):
			if li[i] == 'W':
				ans = i
				flag = 1
				break
		if flag:
			temp.append((ans - 1, 0))
	if li[-1] == 'L':
		ans = n - 1
		flag = 0
		for i in reversed(range(n)):
			if li[i] == 'W':
				flag = 1
				ans = i + 1
				break
		if flag:
			temp.append((ans, n - 1))
	temp.sort(key=lambda x: abs(x[1] - x[0]) + 1)
	between_wins.extend(temp)
	for i in between_wins:
		if i[1] >= i[0]:
			for j in range(i[0], i[1] + 1):
				if k > 0:
					k -= 1
					li[j] = 'W'
				else:
					break
		else:
			for j in reversed(range(i[1], i[0] + 1)):
				if k > 0:
					k -= 1
					li[j] = 'W'
				else:
					break
	if between_wins == []:
		for i in range(min(n, k)):
			li[i] = 'W'
	points = 1 if li[0] == 'W' else 0
	for i in range(1, n):
		if li[i] == 'W' and li[i - 1] == 'W':
			points += 2
		elif li[i] == 'W':
			points += 1
	print(points)
tests = int(input())
for i in range(tests):
	process()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	if s.count('W') == n:
		print(2 * n - 1)
	elif s.count('L') == n:
		print(max(2 * k - 1, 0))
	else:
		score = 0
		if s[0] == 'W':
			score += 1
		for i in range(1, n):
			if s[i] == s[i - 1] == 'W':
				score += 2
			elif s[i] == 'W':
				score += 1
		left = 0
		right = n - 1
		while left < n and s[left] == 'L':
			left += 1
		while right >= 0 and s[right] == 'L':
			right -= 1
		left_dist = left
		right_dist = n - right - 1
		s = s[left + 1:right]
		s = s.split('W')
		s = [len(line) for line in s if line]
		s.sort(reverse=True)
		while s and s[-1] <= k:
			score += s[-1] * 2 + 1
			k -= s[-1]
			s.pop()
		score += k * 2
		print(min(score, 2 * n - 1))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(input().strip())
	from collections import defaultdict
	mp = defaultdict(list)
	i = 0
	while i < n and s[i] == 'L':
		i += 1
	cnt = 0
	lst = i
	while i < n:
		if s[i] == 'L':
			cnt += 1
		else:
			if cnt:
				mp[cnt].append(lst)
			cnt = 0
			lst = i + 1
		i += 1
	for i in sorted(mp.keys()):
		for idx in mp[i]:
			j = idx
			while j < n and s[j] == 'L' and (k > 0):
				s[j] = 'W'
				j += 1
				k -= 1
				if k <= 0:
					break
			if k <= 0:
				break
		if k <= 0:
			break
	i = 0
	mp2 = []
	cnt = 0
	res = 0
	while i < n:
		if s[i] == 'W':
			cnt += 1
		else:
			if cnt:
				res += 1 + 2 * (cnt - 1)
				mp2.append(cnt)
			cnt = 0
		i += 1
	if cnt:
		res += 1 + 2 * (cnt - 1)
		mp2.append(cnt)
	if 'W' in s:
		res += max(0, 2 * min(s.count('L'), k))
		pass
	else:
		res += max(0, 2 * min(s.count('L'), k) - 1)
		pass
	print(res)


import math
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	s = list(input())
	edge = 0
	ans = 0
	f = 0
	for i in s:
		if i == 'W':
			f = 1
			break
	if s[0] == 'W':
		ans = 1
	for i in range(1, n):
		if s[i - 1] == 'W' and s[i] == 'W':
			ans += 2
		elif s[i] == 'W':
			ans += 1
	for i in range(n):
		if s[i] == 'W':
			break
		edge += 1
	for j in range(n - 1, -1, -1):
		if s[j] == 'W':
			break
		else:
			edge += 1
	(st, en) = (i, j)
	l = []
	c = 0
	for i in range(st, en + 1):
		if s[i] == 'L':
			c += 1
		else:
			if c:
				l.append(c)
			c = 0
	l.sort()
	for i in l:
		if i <= k:
			ans += 2 * i + 1
			k -= i
		else:
			edge += i
	able = min(edge, k)
	if f:
		ans += 2 * able
	else:
		ans += 2 * able - 1
	print(max(ans, 0))


t = int(input())
final = []
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input()
	st = 0
	end = n - 1
	sumw = s.count('W')
	if sumw == 0:
		if k >= n:
			final.append(str(n * 2 - 1))
		elif k:
			final.append(str(k * 2 - 1))
		else:
			final.append('0')
		continue
	for i in range(n):
		if s[i] == 'W':
			st = i
			break
	for i in range(n - 1, -1, -1):
		if s[i] == 'W':
			end = i
			break
	temp = 0
	sums = []
	ans = 0
	flag = 0
	for i in range(st, end + 1):
		if s[i] == 'L':
			temp += 1
			flag = 0
		else:
			ans += 1 + flag
			flag = 1
			if temp:
				sums.append(temp)
				temp = 0
	sums.sort()
	for i in sums:
		if k >= i:
			ans += i * 2 + 1
			k -= i
		else:
			ans += k * 2
			k = 0
	left = st + n - 1 - end
	if k >= left:
		ans += left * 2
	else:
		ans += k * 2
	final.append(str(ans))
print('\n'.join(final))


test_cases = int(input())
for test_case in range(test_cases):
	(n, k) = list(map(int, input().split()))
	s = input()
	countl = 1
	countw = 1
	score = 0
	l = []
	w = []
	lstart = 0
	if len(s) == 1 and k > 0:
		score = 1
	else:
		for i in range(n - 1):
			if s[i] == 'L':
				if s[i + 1] == 'L':
					countl += 1
				elif lstart == 0 and w == []:
					lstart = countl
					countl = 1
				else:
					l.append(countl)
					countl = 1
			elif s[i + 1] == 'W':
				countw += 1
			else:
				w.append(countw)
				countw = 1
		l.sort()
		if s[-1] != 'W':
			l.append((countl, 'l'))
		else:
			w.append(countw)
		for i in w:
			score += 2 * i - 1
		if lstart != 0:
			l.append((lstart, 's'))
		if w == []:
			score = 2 * min(l[0][0], k) - 1
			if score < 0:
				score = 0
		else:
			for i in l:
				if type(i) == tuple:
					x = i[0]
					if x <= k:
						score += 2 * x
						k = k - x
					else:
						score += 2 * min(x, k)
						break
				elif i <= k:
					score += 2 * i + 1
					k = k - i
				else:
					score += 2 * k
					break
	print(score)


t = int(input())
arr = []
for _ in range(t):
	(n, k) = tuple(map(int, input().split()))
	arr.append((n, k, input()))
for (n, k, string) in arr:
	numL = 0
	Lchain = string.split('W')
	Lchain = list(map(lambda x: len(x), Lchain))
	Wchain = string.split('L')
	Wchain = list(map(lambda x: len(x), Wchain))
	if k >= sum(Lchain):
		print(2 * len(string) - 1)
		continue
	if len(Lchain) == 1:
		print(max(0, 2 * k - 1))
		continue
	res = 0
	for i in Wchain:
		if i != 0:
			res += 2 * i - 1
	Lchain = [Lchain[i] for i in range(len(Lchain)) if i != 0 and i != len(Lchain) - 1]
	Lchain.sort()
	for i in Lchain:
		if i == 0:
			pass
		elif k >= i:
			res += 2 * i + 1
			k -= i
		else:
			res += 2 * k
			k = 0
			break
	res += 2 * k
	print(res)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	(n, k) = R()
	a = []
	p = 0
	j = 0
	ans = 0
	for i in S():
		j += 1
		if i == 'W':
			if not p:
				p = j
				ans += 1
			else:
				if j - p - 1:
					a += (j - p - 1,)
					ans += 1
				else:
					ans += 2
				p = j
	if not p:
		print(max(0, k * 2 - 1))
		continue
	a.sort(reverse=True)
	while a and k:
		p = a.pop()
		if p <= k:
			ans += p * 2 + 1
			k -= p
		else:
			ans += k * 2
			k = 0
			break
	print(min(n * 2 - 1, ans + k * 2))


t = int(input())
ans = [0 for _ in range(t)]

def score(s):
	ret = 0
	n = len(s)
	for i in range(n):
		if s[i] == 'W':
			if i == 0 or s[i - 1] == 'L':
				ret += 1
			else:
				ret += 2
	return ret
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	if set(s) == set('W'):
		ans[i] = 2 * n - 1
		continue
	if set(s) == set('L'):
		ans[i] = max(2 * min(n, k) - 1, 0)
		continue
	left_gap = 0
	right_gap = 0
	gap = 0
	gaps = []
	for j in range(n):
		if s[j] == 'W':
			if j > 0 and s[j - 1] == 'L':
				if j == gap:
					left_gap = gap
				else:
					gaps.append(gap)
				gap = 0
			continue
		gap += 1
	if gap > 0:
		right_gap = gap
	a = score(s)
	gaps.sort()
	for g in gaps:
		if k >= g:
			a += 2 * g + 1
			k -= g
			continue
		if k > 0:
			a += 2 * k
			k = 0
	cnt = 0
	while k > 0:
		if left_gap > 0:
			a += 2 * min(left_gap, k)
			k -= min(left_gap, k)
			cnt += 1
			left_gap = 0
			continue
		if right_gap > 0:
			a += 2 * min(right_gap, k)
			k -= min(right_gap, k)
			right_gap = 0
			continue
		break
	ans[i] = a
for x in ans:
	print(x)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	w = 0
	l = 0
	otv = 0
	d = []
	for j in range(n):
		if w == 1 and s[j] == 'L':
			l += 1
		if s[j] == 'W':
			otv += 1
			if j != 0:
				if s[j - 1] == 'W':
					otv += 1
			w = 1
			if l != 0:
				d.append(l)
				l = 0
	d.sort()
	j = 0
	while j < len(d) and k >= d[j]:
		otv += 2 * d[j] + 1
		k -= d[j]
		j += 1
	otv += 2 * k
	if w == 0:
		otv = 2 * k - 1
	if otv > 2 * n - 1:
		otv = 2 * n - 1
	if otv < 0:
		otv = 0
	print(otv)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(input())
	(s, l) = (0, 0)
	(ind, sp) = ([], [])
	for i in range(n):
		if a[i] == 'W':
			if i > 0 and a[i - 1] == 'W':
				s += 2
			else:
				s += 1
			ind.append(i)
			l += 1
			if l > 1:
				sp.append([ind[-1], ind[-2], ind[-1] - ind[-2] - 1])
	sp = sorted(sp, key=lambda x: x[2])
	if k == 0:
		print(s)
	elif ind == []:
		print(1 + 2 * min(k - 1, n - 1))
	else:
		k1 = [n, ind[-1], n - ind[-1] - 1]
		k2 = [ind[0], -1, ind[0]]
		ini = s
		if k1[2] > k2[2]:
			sp += [k2, k1]
		else:
			sp += [k1, k2]
		l1 = len(sp)
		for i in range(l1):
			if sp[i][2] == 0:
				continue
			if sp[i][0] == n:
				if k >= sp[i][2]:
					ini += 2 * sp[i][2]
					k -= sp[i][2]
				else:
					ini += 2 * k
					k = 0
			elif k >= sp[i][2]:
				ini += 2 * (sp[i][2] - 1) + 2
				if sp[i][1] != -1:
					ini += 1
				k -= sp[i][2]
			else:
				ini += 2 * (k - 1) + 2
				k = 0
			if k == 0:
				break
		print(ini)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	s = input()
	if 'W' not in s:
		print(max(min(n, k) * 2 - 1, 0))
		continue
	l = s.split('W')[1:-1]
	l = list(filter(None, l))
	l = [len(block) for block in l]
	l.sort()
	ncut = len(l) + 1
	x = s.count('W')
	for i in range(len(l)):
		if k >= l[i]:
			x += l[i]
			k -= l[i]
			ncut -= 1
	print(max(0, min(2 * n - 1, (x + k) * 2 - ncut)))


T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	s = input()
	res = 0
	gaps = []
	gap0 = 0
	gap = 0
	prev = False
	f = True
	for x in s:
		if f:
			if x == 'L':
				gap0 += 1
			else:
				f = False
				res = 1
				prev = True
		elif x == 'L':
			gap += 1
			prev = False
		else:
			res += 1
			if prev:
				res += 1
			else:
				gaps.append(gap)
				gap = 0
			prev = True
	if prev:
		gapN = 0
	else:
		gapN = gap
	gaps.sort()
	nn = len(gaps)
	i = 0
	while i < nn and k >= gaps[i]:
		res += 2 * gaps[i] + 1
		k -= gaps[i]
		i += 1
	if i < nn or k <= gap0 + gap:
		res += 2 * k
	else:
		res += (gap0 + gap) * 2
	if gap0 == n and k > 0:
		res -= 1
	print(res)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = input().rstrip()
	c = a.count('L')
	k = min(k, c)
	out = sum((2 if i > 0 and a[i - 1] == 'W' else 1 for (i, v) in enumerate(a) if v == 'W'))
	if k == 0:
		print(out)
		continue
	if out == 0:
		out -= 1
	out += k * 2
	temp = sorted((len(v) for v in a.split('W')[1:-1] if v))
	for v in temp:
		if v <= k:
			out += 1
			k -= v
		else:
			break
	print(out)


t = int(input())
tag = []
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	(cur, ans) = (k + 5, 0)
	tag.clear()
	for j in range(n):
		if s[j] == 'L':
			cur += 1
		else:
			ans += 1 if cur > 0 else 2
			if cur > 0:
				tag.append(cur)
			cur = 0
	if cur == k + n + 5:
		print(max(0, 2 * min(k, n) - 1))
		continue
	tag.sort()
	for j in range(len(tag)):
		if k >= tag[j]:
			ans = ans + 2 * tag[j]
			ans += 1
			k -= tag[j]
	ans += 2 * k
	ans = min(ans, 2 * n - 1)
	print(ans)


from collections import deque, defaultdict

def solve():
	(n, k) = map(int, input().split())
	s = input()
	clss = []
	cl = fl = ls = 0
	for i in range(n):
		if s[i] == 'L':
			cl += 1
			ls += 1
		elif fl:
			clss.append(cl)
			cl = 0
		else:
			fl = 1
			cl = 0
	s = i = 0
	clss.sort()
	while i < len(clss):
		s += clss[i]
		if s > k:
			break
		i += 1
	cons = len(clss) - i + 1
	w = n - ls
	if ls == n and k == 0:
		print(0)
	elif k >= ls:
		print(2 * n - 1)
	else:
		print(2 * (w + k) - cons)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = input().strip()
	curr = n + 100
	streaks = []
	out = 0
	wins = k
	for i in range(n - 1):
		if s[i] == 'W' and s[i + 1] == 'W':
			out += 1
	for c in s:
		if c == 'W':
			streaks.append(curr)
			curr = 0
			out += 1
			wins += 1
		else:
			curr += 1
	streaks.sort()
	out += 2 * k
	for v in streaks:
		if v > 0 and v <= k:
			k -= v
			out += 1
	print(min([2 * n - 1, out, max(0, 2 * wins - 1)]))


import sys
input = lambda : sys.stdin.readline()
int_arr = lambda : list(map(int, input().split()))
str_arr = lambda : list(map(str, input().split()))
get_str = lambda : map(str, input().split())
get_int = lambda : map(int, input().split())
get_flo = lambda : map(float, input().split())
mod = 1000000007

def solve(n, k, s):
	c = 0
	if s[0] == 'W':
		c = 1
	for i in range(1, n):
		if s[i] == 'W' and s[i - 1] == 'W':
			c += 2
		elif s[i] == 'W':
			c += 1
	if k == 0:
		print(c)
		return
	(l, r) = (0, 0)
	for i in range(n):
		if s[i] == 'W':
			l = i
			break
	for i in range(n - 1, -1, -1):
		if s[i] == 'W':
			r = i
			break
	ans = []
	tmp = 0
	for i in range(l, r + 1):
		if s[i] == 'L':
			tmp += 1
		else:
			if tmp != 0:
				ans.append(tmp)
			tmp = 0
	ans.sort()
	for i in ans:
		if i <= k:
			c += 2 * i + 1
			k -= i
		else:
			c += 2 * k
			k = 0
			break
	if k > 0 and c > 0:
		c += min(n - (r + 1), k) * 2
		k -= n - (r + 1)
		if k > 0:
			c += min(k, l) * 2
	print(c if c != 0 else max(k, 1) * 2 - 1)
for _ in range(int(input())):
	(n, k) = get_int()
	s = str(input())[:-1]
	solve(n, k, s)


from collections import deque
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	initialK = k
	s = input()
	gaps = []
	gapLen = 0
	if s[0] == 'L':
		w = 0
	else:
		w = 1
	for i in range(1, len(s)):
		if s[i] == 'W':
			w += 1
			if gapLen != 0:
				gaps.append(gapLen)
				gapLen = 0
		elif s[i - 1] == 'W':
			gapLen = 1
		elif gapLen != 0:
			gapLen += 1
	if w + k >= n:
		print(2 * n - 1)
		continue
	gaps = deque(sorted(gaps))
	while len(gaps) > 0 and k >= gaps[0]:
		k -= gaps.popleft()
	ans = 2 * (initialK + w) - 1 - len(gaps)
	print(max(0, ans))


import array
T = int(input())
for Tid in range(T):
	(n, k) = map(int, input().split())
	a = input()

	def c1():
		sum = 0
		tmp = k
		for i in range(n):
			if a[i] == 'W':
				sum += 2
			elif tmp != 0:
				(tmp, sum) = (tmp - 1, sum + 2)
		return sum

	def c2():
		(sum, la) = (0, -(1 << 30))
		b = []
		for i in range(n):
			if a[i] == 'W':
				if i == 0 or a[i - 1] == 'L':
					sum += 1
				if i != 0 and a[i - 1] == 'L' and (la > 0):
					b.append(la)
				la = 0
			else:
				la = la + 1
		tmp = k
		b = sorted(b)
		for i in range(len(b)):
			if tmp >= b[i]:
				tmp -= b[i]
				sum -= 1
		return max(sum, 1)
	print(max(c1() - c2(), 0))


from bisect import *
import math
from collections import *
from heapq import *
from itertools import *
inf = 10 ** 18
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(input())
	arr = []
	prev = -1
	if n == 1:
		if k:
			print(1)
		elif s[0] == 'W':
			print(1)
		else:
			print(0)
		continue
	for i in range(n):
		if s[i] == 'W':
			if prev == -1:
				prev = i
			elif i - prev == 1:
				prev = i
			else:
				arr.append(i - prev - 1)
				prev = i
	if s.count('W') + k >= n or len(arr) == 0:
		print(max(0, min(n, s.count('W') + k) * 2 - 1))
	else:
		arr.sort()
		ans = s.count('W')
		cnl = s.count('L')
		par = len(arr) + 1
		for i in arr:
			if i <= k:
				k -= i
				cnl -= i
				par -= 1
				ans += i
		ans += min(k, cnl)
		print(max(0, ans * 2 - par))


for i in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	c = [len(i) for i in list(map(str, s.split('W'))) if len(i) > 0]
	d = [len(i) for i in list(map(str, s.split('L'))) if len(i) > 0]
	t = sum(c)
	if t <= k:
		print(2 * n - 1)
	elif not d:
		print(max(2 * k - 1, 0))
	else:
		g = h = 0
		if s[0] == 'L':
			g = c[0]
			c.pop(0)
		if s[-1] == 'L':
			h = c[-1]
			c.pop()
		if t - g - h <= k:
			print(2 * (n - t + k) - 1)
		else:
			c.sort()
			ans = sum(d) * 2 - len(d)
			while k > 0:
				p = c[0]
				if k - p < 0:
					break
				else:
					ans += 2 * p + 1
				c.pop(0)
				k -= p
			if k > 0:
				ans += 2 * k
			print(ans)


def testcase():
	(n, k) = map(int, input().split())
	s = list(input())
	ans = 0
	if s[0] == 'W':
		ans += 1
	for i in range(1, n):
		if s[i] == 'W':
			ans += 1
			if s[i - 1] == 'W':
				ans += 1
	fw = 0
	while fw < n and s[fw] == 'L':
		fw += 1
	lw = n - 1
	while lw >= 0 and s[lw] == 'L':
		lw -= 1
	gaps = []
	gap = 0
	for i in range(fw, lw + 1):
		if s[i] == 'L':
			gap += 1
		elif gap != 0:
			gaps.append(gap)
			gap = 0
	gaps.sort()
	for gap in gaps:
		if k >= gap:
			ans += 2 * gap + 1
			k -= gap
		else:
			ans += 2 * k
			k = 0
			break
	if k > 0 and lw != -1:
		tl = n - lw - 1
		ans += 2 * min(k, tl)
		k = max(0, k - tl)
	if k > 0:
		sl = fw
		ans += 2 * min(k, sl)
	if fw == n:
		if k == 0:
			ans = 0
		else:
			ans = 2 * k - 1
	print(ans)
	return
t = int(input())
for _ in range(t):
	testcase()


t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().split()))
	s = input()
	suml = 0
	score = 0
	lstl = []
	count = 0
	for j in range(n):
		if j == 0 and s[0] == 'W':
			score += 1
			continue
		elif s[j] == 'L':
			score += 0
		elif s[j] == 'W' and s[j - 1] == 'W':
			score += 2
		elif s[j] == 'W' and s[j - 1] == 'L':
			score += 1
	if k == 0:
		print(score)
		continue
	for j in range(n):
		if s[j] == 'W' and count != 0:
			lstl.append(count)
			count = 0
		elif s[j] == 'L':
			count += 1
	if count != 0:
		lstl.append(count)
	laststreak = 0
	firststreak = 0
	if s[n - 1] == 'L':
		laststreak = lstl[-1]
	if s[0] == 'L':
		firststreak = lstl[0]
	for j in s:
		if j == 'L':
			suml += 1
	if k >= suml:
		print(1 + 2 * (n - 1))
		continue
	elif suml == n:
		print(1 + (k - 1) * 2)
	elif k < suml:
		if s[0] == 'W' and s[n - 1] == 'W':
			lstl.sort()
			for q in range(len(lstl)):
				if k == 0:
					break
				if k >= lstl[q]:
					score += 2 * lstl[q] + 1
					k = k - lstl[q]
				else:
					score += 2 * k
					k = 0
					break
		else:
			if s[0] == 'W' and s[-1] == 'L':
				lstl = lstl[0:len(lstl) - 1]
				lstl.sort()
			elif s[0] == 'L' and s[-1] == 'W':
				lstl = lstl[1:len(lstl)]
				lstl.sort()
			else:
				lstl = lstl[1:len(lstl) - 1]
				lstl.sort()
			for q in range(len(lstl)):
				if k == 0:
					break
				if k >= lstl[q]:
					score += 2 * lstl[q] + 1
					k = k - lstl[q]
				else:
					score += 2 * k
					k = 0
					break
			h = laststreak + firststreak
			if k != 0 and k <= h:
				score += k * 2
		print(score)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	s = input()
	i = 0
	first = 0
	last = 0
	res = 0
	while i < n and s[i] != 'W':
		i += 1
		first += 1
	intervals = []
	while i < n:
		start = i
		while i < n and s[i] == 'W':
			if i > start:
				res += 2
			else:
				res += 1
			i += 1
		if i == n:
			break
		intervals.append(0)
		while i < n and s[i] != 'W':
			intervals[-1] += 1
			i += 1
		if i == n:
			last = intervals.pop()
	intervals.sort()
	if len(intervals) == 0 and first == n:
		print(max(0, min(n, k) * 2 - 1))
	else:
		i = 0
		while k > 0 and i < len(intervals):
			if intervals[i] <= k:
				res += intervals[i] * 2 + 1
				k -= intervals[i]
			else:
				res += 2 * k
				k = 0
			i += 1
		if k > 0:
			res += min(last + first, k) * 2
		print(res)


gans = []
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(input())
	cnt = 1
	u = []
	ok = False
	ans = 0
	for i in range(1, n):
		if a[i] != a[i - 1]:
			if a[i - 1] == 'L':
				u.append([cnt, 0])
				if not ok:
					u[0][1] = 1
			else:
				ans += cnt * 2 - 1
			cnt = 1
			ok = True
		else:
			cnt += 1
	if a[-1] == 'L':
		u.append([cnt, 1])
	else:
		ans += cnt * 2 - 1
	u.sort(key=lambda x: (x[1], x[0]))
	if ans == 0:
		ans = 2 * k - min(1, k)
		gans.append(ans)
		continue
	for i in range(len(u)):
		if u[i][0] > k:
			ans += k * 2
			break
		k -= u[i][0]
		ans += u[i][0] * 2 + 1 - u[i][1]
	gans.append(ans)
print('\n'.join(map(str, gans)))


a = int(input())
for k in range(a):
	(b, n) = [int(k) for k in input().split()]
	r = input()
	len_r = len(r)
	p_W = []
	for x in range(len_r):
		if r[x] == 'W':
			p_W.append(x)
	len_p_W = len(p_W)
	l_d = []
	for y in range(len(p_W) - 1):
		d = p_W[y + 1] - p_W[y]
		l_d.append(d)
	len_l_d = len(l_d)
	if n == 0:
		if p_W == []:
			ans = 0
		else:
			ans = 1
			for x in l_d:
				if x > 1:
					ans += 1
				else:
					ans += 2
	elif p_W == [] or l_d.count(1) == len_l_d or sum(l_d) - len_l_d <= n:
		ans = min(n, 1) + 2 * min(len_p_W + n - 1, len_r - 1)
	else:
		ans = 1
		for x in l_d:
			if x > 1:
				ans += 1
			else:
				ans += 2
		l_d = list(filter(lambda a: a > 1, l_d))
		l_d.sort()
		for x in l_d:
			if x - 1 <= n:
				ans += 2 * (x - 1) + 1
				n -= x - 1
			else:
				ans += 2 * n
				break
	print(ans)


import io
import os
import sys
import math
input = sys.stdin.readline
T = int(input())
for t in range(T):
	(N, K) = map(int, input().split())
	S = input().strip()
	loss = win = 0
	strikes = []
	gaps = []
	current_win = 0
	current_loss = 0
	for (i, s) in enumerate(S):
		if s == 'W':
			current_win += 1
			win += 1
			if current_loss:
				if len(strikes):
					gaps.append(current_loss)
				current_loss = 0
		else:
			current_loss += 1
			loss += 1
			if current_win:
				strikes.append(current_win)
				current_win = 0
	if current_win:
		strikes.append(current_win)
	if K >= loss:
		print(N * 2 - 1)
		continue
	if win == 0:
		print(max(K * 2 - 1, 0))
		continue
	gaps.sort()
	ans = 2 * (win + K) - len(strikes)
	fixed_gaps = 0
	for gap in gaps:
		if gap <= K:
			fixed_gaps += 1
			K -= gap
		else:
			break
	ans += fixed_gaps
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	tmp = k
	s = input()
	k = max(0, n - s.count('W') - k)
	l = [0]
	for i in range(n):
		if i > 0 and s[i - 1] == s[i] == 'W':
			continue
		if s[i] == 'W':
			l.append(0)
		else:
			l[-1] += 1
	if len(l) == 1:
		if s[0] == 'W':
			print(2 * n - 1)
		else:
			print(max(0, 2 * tmp - 1))
		continue
	p = l[0]
	q = l[-1]
	l = sorted(l[1:-1], reverse=True)
	m = len(l)
	s = 0
	(ans1, ans2, ans3, ans4) = (1000000000, 100000000000, 1000000000000, 1000000000000)
	for i in range(len(l)):
		if s >= k:
			ans1 = k * 2 + i
			break
		s += l[i]
	else:
		if s >= k:
			ans1 = k * 2 + m
	s = 0
	for i in range(len(l)):
		if s + p >= k:
			ans2 = k * 2 + i
			break
		s += l[i]
	else:
		if s + p >= k:
			ans2 = k * 2 + m
	s = 0
	for i in range(len(l)):
		if s + q >= k:
			ans3 = k * 2 + i
			break
		s += l[i]
	else:
		if s + q >= k:
			ans3 = k * 2 + m
	s = 0
	for i in range(len(l)):
		if s + p + q >= k:
			ans4 = k * 2 + i
			break
		s += l[i]
	else:
		if s + p + q >= k:
			ans4 = k * 2 + m
	print(n * 2 - 1 - min(ans1, ans2, ans3, ans4))


from collections import deque

def solve():
	(n, k) = map(int, input().split())
	data = list(input())
	data.append('E')
	pointer = 0
	que = []
	combo = 0
	res = 0
	which = 0
	for i in range(n):
		if i == 0:
			if data[i] == 'W':
				which = 1
			else:
				which = -1
			combo = 1
		elif which < 0:
			if data[i] == 'W':
				if i > combo:
					que.append(combo)
				combo = 1
				which = 1
			elif data[i] == 'L':
				combo += 1
		elif which > 0:
			if data[i] == 'W':
				combo += 1
			else:
				res += 2 * combo - 1
				combo = 1
				which = -1
	if combo > 0 and which > 0:
		res += 2 * combo - 1
	que.sort()
	que = deque(que)
	cheat = k
	if res == 0:
		print(min(2 * n - 1, max(2 * k - 1, 0)))
		return
	while que and que[0] <= cheat:
		v = que.popleft()
		res += 2 * v + 1
		cheat -= v
	res += 2 * cheat
	ans = min(res, 2 * n - 1)
	print(ans)
	return

def main():
	t = int(input())
	for i in range(t):
		solve()
	return
main()


def examA():
	T = I()
	ans = []
	for _ in range(T):
		N = I()
		B = LI()
		if sum(B) == 0:
			print('NO')
			continue
		print('YES')
		B.sort()
		for i in range(N):
			cur = []
			now = 0
			for j in range(N):
				now += B[i - j]
				if now == 0:
					break
				cur.append(B[i - j])
			if len(cur) == N:
				print(' '.join(map(str, cur)))
				break
	return

def examB():
	T = I()
	ans = []
	for _ in range(T):
		(N, K) = LI()
		S = SI()
		L = []
		W = 0
		WW = 0
		cur = 0
		l = -inf
		flag_W = False
		for s in S:
			if s == 'W':
				WW += 1
				if flag_W:
					cur += 2
					continue
				if l > 0:
					L.append(l)
				l = 0
				flag_W = True
				W += 1
				cur += 1
			else:
				flag_W = False
				l += 1
		if WW == 0:
			cur = max(0, 2 * K - 1)
		elif K == 0:
			pass
		elif N - WW <= K:
			cur = 2 * N - 1
		else:
			L.sort()
			for i in range(len(L)):
				a = L[i]
				if a <= K:
					cur += 1 + 2 * a
					K -= a
				else:
					cur += 2 * K
					K = 0
					break
			if K > 0:
				cur += 2 * K
		ans.append(min(2 * N - 1, cur))
	for v in ans:
		print(v)
	return

def examC():
	T = I()
	ans = []
	for _ in range(T):
		cur = 0
		ans.append(cur)
	for v in ans:
		print(v)
	return

def examD():
	ans = 0
	print(ans)
	return

def examE():
	ans = 0
	print(ans)
	return

def examF():
	ans = 0
	print(ans)
	return
from decimal import getcontext, Decimal as dec
import sys, bisect, heapq
from copy import deepcopy
from heapq import heappop, heappush, heapify
from collections import Counter, defaultdict, deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def I():
	return int(input())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def DI():
	return dec(input())

def LDI():
	return list(map(dec, sys.stdin.readline().split()))

def LSI():
	return list(map(str, sys.stdin.readline().split()))

def LS():
	return sys.stdin.readline().split()

def SI():
	return sys.stdin.readline().strip()
global mod, mod2, inf, alphabet, _ep
mod = 10 ** 9 + 7
mod2 = 998244353
inf = 10 ** 18
_ep = dec('0.000000000001')
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}
getcontext().prec = 28
sys.setrecursionlimit(2 * 10 ** 5)
examB()


t = int(input())
for _ in range(t):
	(n, k) = [int(m) for m in input().split()]
	s = list(input())
	firstwin = s.index('W') if 'W' in s else -1
	if firstwin == -1:
		print(max(min(k, len(s)) * 2 - 1, 0))
		continue
	left = firstwin
	noleft = True
	A = []
	(front, back) = (None, None)
	if left != 0:
		front = (0, left)
	for i in range(firstwin, len(s)):
		if s[i] == 'L' and noleft:
			left = i
			noleft = False
		elif s[i] == 'W' and (not noleft):
			A.append((left, i))
			noleft = True
	if not noleft:
		back = (left, len(s))
	A.sort(key=lambda a: a[1] - a[0])
	if k > 0:
		for a in A:
			for i in range(*a):
				k -= 1
				s[i] = 'W'
				if k <= 0:
					break
			if k <= 0:
				break
	if k > 0:
		if back:
			for i in range(*back):
				s[i] = 'W'
				k -= 1
				if k <= 0:
					break
		if front and k > 0:
			for i in reversed(range(*front)):
				s[i] = 'W'
				k -= 1
				if k <= 0:
					break
	res = 0 if s[0] == 'L' else 1
	for i in range(1, len(s)):
		if s[i] == 'W' == s[i - 1]:
			res += 2
		elif s[i] == 'W':
			res += 1
	print(res)


from sys import stdin, stdout
import math
import heapq
import collections
input = stdin.readline

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

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

def inputstring():
	return [x for x in input()]

def inputstrings():
	return [x for x in input().split()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	(n, k) = inputnums()
	s = inputstring()
	losingstreak = []
	winningstreak = 0
	wins = 0
	losses = 0
	curloss = 0
	for i in range(n):
		if s[i] == 'W':
			wins += 1
			if i == 0 or s[i - 1] == 'L':
				winningstreak += 1
		else:
			losses += 1
			curloss += 1
			if i == n - 1 or s[i + 1] == 'W':
				losingstreak.append(curloss)
				curloss = 0
	if k >= losses:
		print(2 * n - 1)
		continue
	if wins == 0:
		if k == 0:
			print(0)
			continue
		else:
			print(2 * k - 1)
			continue
	if s[0] == 'L':
		losingstreak[0] = 1000000000.0
	if s[n - 1] == 'L':
		losingstreak[len(losingstreak) - 1] = 1000000000.0
	losingstreak.sort()
	wins += k
	for i in range(len(losingstreak)):
		if k < losingstreak[i]:
			break
		else:
			winningstreak -= 1
			k -= losingstreak[i]
	print(2 * wins - winningstreak)


from itertools import groupby
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	if k >= s.count('L'):
		print(n * 2 - 1)
	else:
		s = s.strip('L')
		group = []
		for (i, g) in groupby(s):
			if i == 'L':
				group.append(len(list(g)))
		group.sort()
		(i, m) = (0, len(group))
		r = k
		while i < m and r >= group[i]:
			r -= group[i]
			i += 1
		ans = (s.count('W') + k) * 2 - (m + 1 - i)
		print(max(0, ans))


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = ip()
for _ in range(t):
	(n, k) = inp()
	s = ips()
	if s.count('L') == n:
		ans = 0
		for i in range(k):
			if i == 0:
				ans += 1
			else:
				ans += 2
		k = 0
	else:
		ans = 0
		win = 0
		for i in range(n):
			if s[i] == 'W':
				if win == 0:
					ans += 1
				else:
					ans += 2
				win += 1
			else:
				win = 0
		ct = 0
		gap = []
		for i in range(n):
			if s[i] == 'L':
				ct += 1
			elif ct != 0:
				gap.append(ct)
				ct = 0
		if ct != 0:
			gap.append(ct)
		if s[0] == 'L':
			gap.pop(0)
		if s[-1] == 'L':
			gap.pop()
		gap.sort()
		for i in gap:
			if k >= i:
				ans += 2 * i
				k -= i
				ans += 1
			else:
				ans += 2 * k
				k = 0
		if k > 0:
			flag = True
			if s[-1] == 'L':
				for i in range(n - 1, -1, -1):
					if k == 0:
						break
					elif s[i] == 'W':
						flag = False
						break
					else:
						ans += 2
						k -= 1
			if s[0] == 'L':
				flag = False
				for i in range(n):
					if k == 0:
						break
					elif s[i] == 'W':
						flag = True
						break
					else:
						ans += 2
						k -= 1
	lose = s.count('L')
	if lose <= k:
		ans = 0
		for i in range(n):
			if i == 0:
				ans += 1
			else:
				ans += 2
	out(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	inp = input().lower()
	k = min(k, inp.count('l'))
	ans = inp.count('w') + tuple(zip(inp, 'l' + inp)).count('ww') + k * 2
	if 'w' in inp:
		inp2 = []
		cur = -1
		for c in inp:
			if cur != -1:
				if c == 'l':
					cur += 1
				else:
					inp2.append(cur)
			if c == 'w':
				cur = 0
		inp2.sort()
		for inp2i in inp2:
			if inp2i > k:
				break
			k -= inp2i
			ans += 1
	else:
		ans = max(ans - 1, 0)
	print(ans)


cases = int(input())
for t in range(cases):
	(n, k) = list(map(int, input().split()))
	s = input()
	fw = s.find('W')
	lw = s.rfind('W')
	s = list(s)
	ls = []
	for i in range(fw + 1, n):
		if s[i] == 'L' and s[i - 1] == 'W':
			st = i
		elif s[i] == 'W' and s[i - 1] == 'L':
			ls.append([i - st, st, i])
	ls = sorted(ls)
	f = 0
	c = 0
	for (l, i, j) in ls:
		for m in range(i, j):
			if c < k:
				s[m] = 'W'
				c += 1
			else:
				f = 1
				break
		if f == 1:
			break
	if f == 0:
		for i in range(lw + 1, n):
			if c < k:
				s[i] = 'W'
				c += 1
			else:
				f = 1
				break
	if f == 0:
		for i in range(fw - 1, -1, -1):
			if c < k:
				s[i] = 'W'
				c += 1
			else:
				f = 1
				break
	out = 0
	for i in range(n):
		if i == 0 and s[i] == 'W':
			out += 1
		elif i > 0 and s[i] == 'W' and (s[i - 1] == 'L'):
			out += 1
		elif i > 0 and s[i] == 'W' and (s[i - 1] == 'W'):
			out += 2
	print(out)


from sys import stdin
input = stdin.readline

def A():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		if sum(a) == 0:
			print('NO')
		elif sum(a) > 0:
			a.sort(reverse=True)
			print('YES')
			print(*a)
		else:
			a.sort()
			print('YES')
			print(*a)

def B():
	from collections import deque
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		s = [bool(ord(x) - ord('L')) for x in input().rstrip()]
		lastGame = False
		score = 0
		for i in range(n):
			if s[i]:
				if lastGame:
					score += 2
				else:
					score += 1
				lastGame = True
			else:
				lastGame = False
		startW = 0
		endW = n - 1
		while startW < n and (not s[startW]):
			startW += 1
		while endW >= 0 and (not s[endW]):
			endW -= 1
		streak = 0
		wlws = deque()
		for i in range(startW + 1, endW + 1):
			if s[i] and streak > 0:
				wlws.append(streak)
				streak = 0
			elif not s[i]:
				streak += 1
		wlws = sorted(list(wlws))
		j = 0
		while j < len(wlws) and k >= wlws[j]:
			score += 2 * wlws[j] + 1
			k -= wlws[j]
			j += 1
		if k > 0:
			remainingLs = startW + (n - 1 - endW)
			if startW == n:
				remainingLs = n
				score -= 1
			if j < len(wlws):
				remainingLs = wlws[j]
			score += min(remainingLs, k) * 2
		print(score)

def C():
	t = int(input())
	for _ in range(t):
		print(t)

def D():
	t = int(input())
	for _ in range(t):
		print(t)
B()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = str(input())
	base = 0
	for i in range(n):
		if s[i] == 'W':
			if i != 0:
				if s[i - 1] == 'W':
					base += 2
				else:
					base += 1
			else:
				base += 1
	if base == 0:
		x = n
		if n == 1:
			if k >= 1:
				ans = 1
			else:
				ans = 0
		elif n == 2:
			if k >= 2:
				ans = 3
			elif k == 1:
				ans = 1
			else:
				ans = 0
		elif k >= x:
			ans = 2 * x - 1
		elif k == 0:
			ans = 0
		elif k == 1:
			ans = 1
		else:
			ans = 1 + (k - 1) * 2
		print(ans + base)
		continue
	X = []
	cur = s[0]
	cnt = 0
	for i in range(n):
		if cur == s[i]:
			cnt += 1
		else:
			if cur == 'L':
				X.append([cnt, 0])
			cnt = 1
			cur = s[i]
	else:
		if cur == 'L':
			X.append([cnt, 1])
	if s[0] == 'L':
		X[0][1] = 1
	X.sort(key=lambda x: (x[1], x[0]))
	ans = 0
	for (x, j) in X:
		if k >= x:
			if j != 1:
				ans += 2 * x + 1
			else:
				ans += 2 * x
			k -= x
		else:
			ans += k * 2
			break
	print(ans + base)


import sys, io, os
z = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
o = []
for _ in range(int(z())):
	(n, k) = map(int, z().split())
	s = z().strip()
	b = c = p = r = 0
	l = []
	for i in s:
		if i % 2:
			if b:
				if c:
					l.append(c)
					c = 0
			else:
				b = 1
			r += 1 + (i == p)
		elif b:
			c += 1
		p = i
	l.sort(reverse=True)
	while l:
		v = l.pop()
		if k >= v:
			k -= v
			r += 2 * v + 1
		else:
			break
	if r == 0:
		r = -1
	r += 2 * k
	o.append(str(min(max(r, 0), 2 * n - 1)))
print('\n'.join(o))


t = int(input())
ans = []
for test in range(t):
	(n, k) = [int(i) for i in input().split()]
	a = input()
	loses = sum([1 for i in a if i == 'L'])
	if 'W' not in a:
		ans.append(max(0, k * 2 - 1))
	elif loses <= k:
		ans.append(len(a) * 2 - 1)
	else:
		losing = False
		left = a.find('W')
		segs = []
		cost = 0
		for i in range(left, n):
			if losing is True and a[i] == 'W':
				segs.append(i - left)
				left = i
				losing = False
			elif losing is False and a[i] == 'L':
				cost += (i - left) * 2 - 1
				left = i
				losing = True
		if a[-1] == 'W':
			cost += (n - left) * 2 - 1
		total = sum(segs)
		if k > total:
			ans.append(cost + 2 * total + len(segs) + (k - total) * 2)
		else:
			segs.sort()
			cs = 0
			left = 0
			for (i, seg) in enumerate(segs):
				if k >= cs + seg:
					cs += seg
					left = i + 1
				else:
					break
			ans.append(cost + 2 * cs + left + (k - cs) * 2)
print(*ans, sep='\n')


def f(n, k, s):
	score = 0
	arr = []
	sm = 0
	if 'W' not in s:
		return max(min(n, k) * 2 - 1, 0)
	arr = s.split('W')[1:-1]
	arr = list(filter(None, arr))
	arr = [len(i) for i in arr]
	arr.sort()
	sm = s.count('W')
	ncut = len(arr) + 1
	for i in range(len(arr)):
		if k >= arr[i]:
			sm += arr[i]
			k -= arr[i]
			ncut -= 1
	return max(0, min(2 * n - 1, (sm + k) * 2 - ncut))
t = int(input())
for x in range(t):
	(n, k) = list(map(int, input().split()))
	s = input()
	h = f(n, k, s)
	print(h)


from functools import reduce
import os
import sys
from collections import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007
inf = 1e+18
div = 998244353
for _ in range(inn()):
	(n, k) = value()
	a = [str(x) for x in input()]
	ans = 0
	c = 0
	if len(set(a)) == 1 and a[0] == 'L':
		print(max(0, k * 2 - 1))
		continue
	for i in range(n):
		if a[i] == 'W':
			if i > 0 and a[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
		else:
			c += 1
	i = 0
	while i < n and a[i] == 'L':
		i += 1
	j = n - 1
	while j >= 0 and a[j] == 'L':
		j -= 1
	res = []
	while i < j:
		val = i
		while i < j and a[i] == 'L':
			i += 1
		if i - val > 0:
			res += [i - val]
		else:
			i += 1
	res.sort()
	for i in res:
		if i > k:
			break
		ans += i * 2 + 1
		k -= i
		c -= i
	ans += min(c, k) * 2
	print(min((n - 1) * 2 + 1, ans))


import sys as _sys
WIN = 'W'
LOSE = 'L'

def main():
	t = int(input())
	for i_t in range(t):
		(n, k) = _read_ints()
		s = _read_line()
		result = find_max_score_after_changing(s, k)
		print(result)

def _read_line():
	result = _sys.stdin.readline()
	assert result[-1] == '\n'
	return result[:-1]

def _read_ints():
	return map(int, _read_line().split())

def find_max_score_after_changing(games_results, changes_n):
	if len(games_results) == 0:
		return 0
	if len(games_results) == 1:
		if games_results[0] == WIN:
			result = 1
		elif changes_n > 0:
			result = 1
		else:
			result = 0
		return result
	lose_n = games_results.count(LOSE)
	changes_n = min(changes_n, lose_n)
	if lose_n == len(games_results):
		if changes_n == 0:
			result = 0
		else:
			result = 2 * changes_n - 1
		return result
	curr_score = 1 if games_results[0] == WIN else 0
	for i in range(1, len(games_results)):
		if games_results[i] == WIN:
			if games_results[i - 1] == WIN:
				curr_score += 2
			else:
				curr_score += 1
	empty_spaces = games_results.replace(WIN, ' ').split()
	if games_results[0] == LOSE:
		empty_spaces = empty_spaces[1:]
	if games_results[-1] == LOSE:
		empty_spaces = empty_spaces[:-1]
	distances_between_islands = sorted(map(len, empty_spaces))
	changes_lost = 0
	islands_united = 0
	for distance in distances_between_islands:
		if distance <= changes_n:
			changes_lost += distance
			changes_n -= distance
			islands_united += 1
		else:
			changes_lost += changes_n
			changes_n = 0
			break
	curr_score += (changes_lost + changes_n) * 2
	curr_score += islands_united
	return curr_score
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	ar = []
	i = 0
	single = []
	while i < n and s[i] == 'L':
		i += 1
	if i == n:
		if k > 0:
			print(k * 2 - 1)
		else:
			print(0)
		continue
	if i != 0:
		single.append(i)
	double = []
	f = False
	cnt = 0
	ans = 0
	while i < n:
		if s[i] == 'L':
			if not f:
				f = True
			cnt += 1
		elif f:
			double.append(cnt)
			f = False
			cnt = 0
			ans += 1
		else:
			add = 0
			if i > 0 and s[i - 1] == 'W':
				add = 1
			ans += 1 + add
		i += 1
	if cnt:
		single.append(cnt)
	double.sort()
	single.sort()
	i = 0
	while k > 0 and i < len(double):
		if double[i] <= k:
			k -= double[i]
			ans += double[i] * 2 + 1
		else:
			ans += k * 2
			k = 0
		i += 1
	i = 0
	while k > 0 and i < len(single):
		if single[i] <= k:
			k -= single[i]
			ans += single[i] * 2
		else:
			ans += k * 2
			k = 0
		i += 1
	print(ans)


import itertools
import math
import sys
from collections import defaultdict

def stdinWrapper():
	data = '9\n5 2\nWLWLL\n6 5\nLLLWWL\n7 1\nLWLWLWL\n15 5\nWWWLLLWWWLLLWWW\n40 7\nLLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL\n1 0\nL\n1 1\nL\n6 1\nWLLWLW\n5 2\nLWLWL\n'
	for line in data.split('\n'):
		yield line
if '--debug' not in sys.argv:

	def stdinWrapper():
		while True:
			yield sys.stdin.readline()
inputs = stdinWrapper()

def inputWrapper():
	return next(inputs)

def getType(_type):
	return _type(inputWrapper())

def getArray(_type):
	return [_type(x) for x in inputWrapper().split()]

def tuplerize(method):

	def wrap(*args, **kwargs):
		res = method(*args, **kwargs)
		if not isinstance(res, (tuple, list)):
			res = (res,)
		return res
	return wrap

@tuplerize
def solve(k, games):
	wins = 0
	loses = 0
	win_streaks = 0
	gaps = []
	for i in range(len(games)):
		if games[i] == 'W':
			wins += 1
			if i == 0 or games[i - 1] == 'L':
				win_streaks += 1
		else:
			loses += 1
			if i == 0 or games[i - 1] == 'W':
				gaps.append(0)
			gaps[-1] += 1
	if k >= loses:
		return 2 * len(games) - 1
	if wins == 0:
		if k == 0:
			return 0
		return 2 * k - 1
	if games[0] == 'L':
		gaps[0] = float('inf')
	if games[-1] == 'L':
		gaps[-1] = float('inf')
	gaps = sorted(gaps)
	wins += k
	for gap in gaps:
		if gap > k:
			break
		k -= gap
		win_streaks -= 1
	return 2 * wins - win_streaks
t = getType(int)
for _ in range(t):
	(n, k) = getArray(int)
	games = input()
	res = solve(k, games)
	print(*res)


from collections import *
t = int(input())
while t:
	t -= 1
	(n, k) = [int(x) for x in input().split()]
	s = input()
	if 'W' not in s:
		print(max(0, 1 + 2 * (k - 1)))
	else:
		startl = s.find('W')
		endl = s[::-1].find('W')
		terminal = startl + endl
		nns = ['W']
		ans = 0
		for i in range(startl + 1, n - endl):
			if s[i - 1] == 'W' and s[i] == 'W':
				ans += 2
			else:
				nns.append(s[i])
		s = ''.join(nns)
		n = len(s)
		d = defaultdict(lambda : 0)
		pre = 0
		for i in range(1, n):
			if s[i] == 'W':
				d[i - pre - 1] += 1
				pre = i
		ns = ['W']
		nrr = []
		for key in d:
			nrr.append([key, d[key]])
		nrr.sort()
		for (i, j) in nrr:
			ns.append(('L' * i + 'W') * j)
		ns = ''.join(ns)

		def score():
			ans = 1
			left = k
			N = len(ns)
			pre = False
			for i in range(1, N):
				if ns[i] == 'W':
					if pre or ns[i - 1] == 'W':
						ans += 2
					else:
						ans += 1
					continue
				if left == 0:
					pre = False
					continue
				pre = True
				ans += 2
				left -= 1
			return [ans, left]
		(temp, left) = score()
		ans += temp
		ans += 2 * min(left, terminal)
		print(max(ans, 0))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	L = s.count('L')
	W = s.count('W')
	if L <= k:
		print(2 * (n - 1) + 1)
		continue
	if L == n and k != 0:
		print((k - 1) * 2 + 1)
		continue
	count = 0
	p = 0
	if s[0] == 'W':
		count += 1
		p = 1
	for i in range(1, n):
		if s[i] == 'W' and p:
			count += 2
		elif s[i] == 'W':
			count += 1
			p = 1
		else:
			p = 0
			continue
	if k == 0:
		print(count)
		continue
	temp = s[::-1]
	t = s
	for i in range(n):
		if temp[i] == 'L':
			continue
		else:
			break
	temp = temp[i:]
	temp = temp[::-1]
	s = temp
	m = i
	l = []
	p = 0
	c = 0
	for i in range(1, len(s)):
		if s[i - 1] == 'W' and s[i] == 'L':
			c += 1
			p = 1
		elif s[i - 1] == 'L' and s[i] == 'L' and p:
			c += 1
		elif s[i - 1] == 'L' and s[i] == 'W':
			p = 0
			if c != 0:
				l.append(c)
			c = 0
		else:
			continue
	if c != 0:
		l.append(c)
	l.sort()
	for i in l:
		if k <= 0:
			break
		if k >= i:
			k -= i
			count += 2 * i + 1
		else:
			break
	if len(l) and k <= max(l):
		count += k * 2
		print(count)
	elif m > k:
		count = count + k * 2
		k = 0
		print(count)
	else:
		count += m * 2
		k -= m
		for i in range(n):
			if t[i] == 'W':
				break
		if i > k:
			print(count + k * 2)
		else:
			print(count + (k - i) * 2)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ik = k
	sg = input().strip()
	gaps = []
	l = len(sg)
	wins = 0
	win_streaks = 0
	i = 0
	lcnt = 0
	temp = 0
	while i < l:
		if sg[i] == 'W':
			break
		i += 1
		temp += 1
	filled_gaps = 0
	while i < l:
		if sg[i] == 'W':
			win_streaks += 1
			while i < l and sg[i] == 'W':
				wins += 1
				i += 1
		if i < l and sg[i] == 'L':
			lcnt = 0
			while i < l and sg[i] == 'L':
				lcnt += 1
				i += 1
			else:
				if i < l and sg[i] == 'W':
					gaps.append(lcnt)
				else:
					temp += lcnt
	gaps.sort()
	gap_l = len(gaps)
	j = 0
	while k > 0 and j < gap_l:
		if gaps[j] <= k:
			k -= gaps[j]
			filled_gaps += 1
		j += 1
	if k > 0 and temp > 0 and (wins == 0):
		win_streaks += 1
	score = 2 * min(wins + ik, l) - win_streaks + filled_gaps
	print(score)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = input()
	s = 'L' + s + 'W'
	a = []
	p = 0
	c = 0
	koL = 0
	sum = 0
	for i in range(1, n + 2):
		if s[i] == 'W' and p == 0:
			p = 1
			if i != 1:
				a.append(c)
			c = 0
			if i != n + 1:
				sum += 1
		elif s[i] == 'W' and p == 1 and (i != n + 1):
			sum += 2
		if s[i] == 'L':
			p = 0
			c += 1
			koL += 1
	if s[n] == 'L':
		a.pop()
	if s[1] == 'L' and len(a) != 0:
		a.pop(0)
	if koL <= k:
		print(2 * n - 1)
	else:
		a.sort()
		cum = 0
		p = 0
		for i in range(len(a)):
			if cum + a[i] <= k:
				cum += a[i]
				p += 1
			else:
				break
		if sum == 0 and k != 0:
			print(2 * k - 1)
		else:
			print(sum + 2 * k + p)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	check = [0] * (n + 1)
	loose = 0
	(a, b) = (0, 0)
	(wins, win_streak) = (0, 1)
	c = 0
	for i in s:
		if i == 'L':
			c += 1
		else:
			break
	for i in range(c, n):
		if s[i] == 'W':
			wins += 1
			if loose > 0:
				check[loose] += 1
			loose = 0
		else:
			loose += 1
		if i < n - 1:
			if s[i:i + 2] == 'WL' and b == 0:
				a = 1
			if s[i:i + 2] == 'LW' and a == 1:
				b = 1
			if a == 1 and b == 1:
				a = b = 0
				win_streak += 1
	if n - wins > k:
		wins += k
		for i in range(1, n + 1):
			temp = i * check[i]
			if k >= temp:
				k -= temp
				win_streak -= check[i]
			else:
				win_streak -= k // i
				break
		print(max(2 * wins - win_streak, 0))
	else:
		print(2 * n - 1)


def count(s):
	wins = 0
	l = 0
	arr = []
	prev = None
	for e in s:
		if e == 'L':
			if prev == 'W' or l > 0:
				l += 1
		if e == 'W':
			wins += 1
			if l > 0:
				arr.append(l)
				l = 0
		prev = e
	return (wins, arr)
t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	s = [c for c in input()]
	(wins, arr) = count(s)
	streaks = len(arr) + 1
	if wins == 0:
		print(max(2 * min(n, k) - 1, 0))
	elif wins + k >= n:
		print(2 * n - 1)
	else:
		kt = k
		arr.sort(reverse=True)
		while kt > 0 and len(arr) > 0:
			kt -= arr.pop()
			if kt >= 0:
				streaks -= 1
		print(2 * (k + wins) - streaks)


for t in range(int(input())):
	(n, k) = map(int, input().split())
	h = input()
	if k >= h.count('L'):
		print(2 * n - 1)
	elif n == 0:
		print(0)
	elif 'W' not in h:
		print(max(2 * k - 1, 0))
	else:
		h = h.strip('L')
		n = len(h)
		score = 0
		prev = 'L'
		i = 0
		l = []
		while i < n:
			if h[i] == 'W':
				if prev == 'L':
					prev = 'W'
					score += 1
				else:
					score += 2
			elif prev == 'W':
				l.append(1)
				prev = 'L'
			else:
				l[-1] += 1
			i += 1
		l.sort()
		while l and k >= l[0]:
			temp = l.pop(0)
			score += 2 * temp + 1
			k -= temp
		score += 2 * k
		print(score)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = input()
	bet = []
	score = 0
	counter = 0
	total = 0
	flag = -1
	for x in a:
		if x == 'W':
			if flag == 0:
				bet.append(counter)
				counter = 0
			if flag <= 0:
				score += 1
			else:
				score += 2
			flag = 1
		else:
			if flag == 1 or flag == 0:
				counter += 1
				flag = 0
			total += 1
	if total == n and k > 0:
		score = -1
	else:
		bet.sort()
		for x in bet:
			if x <= k:
				k = k - x
				total = total - x
				score += x * 2 + 1
	if k > total:
		k = total
	score += k * 2
	print(score)


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	string = list(input())
	lis = []
	i = 0
	j = n - 1
	counter = 0
	for _i_ in string:
		if _i_ != 'W':
			counter += 1
			i += 1
		else:
			break
	b1 = (counter, 0)
	counter = 0
	for _i_ in reversed(string):
		if _i_ != 'W':
			counter += 1
			j -= 1
		else:
			break
	b2 = (counter, j + 1)
	while i <= j:
		counter = 0
		if string[i] == 'L':
			q = i
			while string[i] == 'L':
				counter += 1
				i += 1
			lis.append((counter, q))
		else:
			i += 1
	lis.sort()
	for i in lis:
		if k <= 0:
			break
		count = i[0]
		j = i[1]
		for i in range(j, j + count):
			string[i] = 'W'
			k -= 1
			if k <= 0:
				break
	(c, index) = b1
	for i in range(index + c - 1, index - 1, -1):
		if k == 0:
			break
		else:
			string[i] = 'W'
			k -= 1
	(c, index) = b2
	for i in range(index, index + c):
		if k == 0:
			break
		else:
			string[i] = 'W'
			k -= 1
	prev = 'L'
	count = 0
	for i in string:
		if i == 'W' and prev == 'W':
			count += 2
		elif i == 'W':
			count += 1
		prev = i
	print(count)


T = int(input())
for case in range(T):
	(m, n) = [int(x) for x in input().split()]
	s = input()
	lsw = sorted([x for x in s.split('L') if len(x)])
	points = 0
	for e in lsw:
		points += len(e) * 2 - 1
	ll = [x for x in s.split('W') if len(x)]
	ends = 0
	if s[0] == 'L':
		ends += len(ll.pop(0))
	if len(ll) and s[-1] == 'L':
		ends += len(ll.pop())
	ls = sorted(ll)
	c = 0
	full = True
	for e in ls:
		if n >= len(e):
			n -= len(e)
			c += len(e) * 2 + 1
		else:
			c += n * 2
			n = 0
			full = False
	if n != 0:
		c += min(n, ends) * 2
		if 'W' not in s:
			c -= 1
	print(c + points)


def solve():
	(n, k) = map(int, input().split())
	s = list(input())
	if n == 1:
		print(1 if s[0] == 'W' or k > 0 else 0)
		return
	if not 'W' in s:
		print(min(k, n) * 2 - 1 if k > 0 else 0)
		return
	ans = 0
	arr = []
	arr2 = 0
	i = 0
	for i in range(n):
		if s[i] == 'W':
			if i > 0 and s[i - 1] == 'W':
				ans += 2
			else:
				ans += 1
	i = 0
	while i < n:
		if s[i] == 'W':
			i += 1
			continue
		j = i
		while j < n and s[j] == s[i]:
			j += 1
		if j == n or i == 0:
			arr2 += j - i
		else:
			arr.append(j - i)
		i = j
	arr.sort()
	for c in arr:
		if c > k:
			arr2 += c
			continue
		ans += c * 2 + 1
		k -= c
	ans += min(k * 2, arr2 * 2)
	print(ans)
t = int(input())
for _ in range(t):
	solve()


import sys
read = lambda : sys.stdin.readline().strip()
readi = lambda : map(int, read().split())
from collections import *
from math import *
for _ in range(int(read())):
	(n, k) = readi()
	s = read()
	gaps = list()
	temp = 0
	sc = s.strip('L')
	if len(sc) == 0:
		print(max(min(n, k) * 2 - 1, 0))
		continue
	for c in sc:
		if c == 'L':
			temp += 1
		elif temp > 0:
			gaps.append(temp)
			temp = 0
	if temp > 0:
		gaps.append(temp)
	gaps.sort()
	increment = 0
	for gap in gaps:
		if gap <= k:
			increment += gap * 2 + 1
			k -= gap
		else:
			increment += k * 2
			k = 0
			break
	increment += min(k, len(s) - len(sc)) * 2
	baseAns = 0
	temp = 0
	for c in s:
		if c == 'W':
			if temp > 0:
				baseAns += 2
			else:
				baseAns += 1
			temp += 1
		else:
			temp = 0
	print(increment + baseAns)


from sys import stdin, stdout
from collections import *
from math import ceil, floor, log, gcd
st = lambda : list(stdin.readline().strip())
li = lambda : list(map(int, stdin.readline().split()))
mp = lambda : map(int, stdin.readline().split())
inp = lambda : int(stdin.readline())
pr = lambda n: stdout.write(str(n) + '\n')
mod = 1000000007
INF = float('inf')

def solve():
	(n, k) = mp()
	s = st()
	if s.count('W') == 0:
		print(max(0, 2 * k - 1))
		return
	ans = 0
	W = 0
	cur = 0
	w = 0
	x = []
	for i in range(n):
		if s[i] == 'W':
			if cur:
				x.append(cur)
				cur = 0
			ans += 1
			w += 1
			if W:
				ans += 1
			W = 1
		else:
			W = 0
			if w:
				cur += 1
	k = min(k, n - w)
	ans += 2 * k
	x.sort()
	for i in x:
		if i <= k:
			ans += 1
			k -= i
	pr(ans)
for _ in range(inp()):
	solve()


def solve(n, k, games):
	(W, L) = ('W', 'L')
	if n == 1:
		if games[0] == L and k == 0:
			return 0
		return 1
	gl = []
	wins = 0
	scores = 0
	if games[0] == W:
		scores += 1
		wins += 1
	else:
		gl.append(1)
	for i in range(1, n):
		if games[i] == W:
			wins += 1
			if games[i - 1] == W:
				scores += 2
			else:
				scores += 1
		elif games[i - 1] == W:
			gl.append(1)
		else:
			gl[-1] += 1
	m = wins + k
	if m >= n:
		return 2 * n - 1
	if k == 0:
		return scores
	if wins == 0:
		return 2 * k - 1
	if games[0] == L:
		gl.pop(0)
	if games[-1] == L:
		gl.pop()
	a = 0
	gl.sort()
	c = 0
	for i in range(len(gl)):
		c += gl[i]
		if c <= k:
			a += 1
		else:
			break
	return scores + a + 2 * k
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	games = input()
	print(solve(n, k, games))


import sys
t = int(sys.stdin.readline().strip())
for _ in range(t):
	arr = []
	(n, k) = map(int, sys.stdin.readline().strip().split())
	s = input()
	ind = 0
	while ind != n and s[ind] == 'L':
		ind += 1
	if ind == n:
		if k >= n:
			print(2 * n - 1)
		else:
			print(max(2 * k - 1, 0))
		continue
	count = -1
	current = 0
	for i in range(ind, n):
		if s[i] == 'W':
			if count > 0:
				current += 1
				arr += [count]
			elif count < 0:
				current += 1
			else:
				current += 2
			count = 0
		else:
			count += 1
	change = 0
	arr.sort()
	delta = 0
	for i in range(len(arr)):
		if change + arr[i] <= k:
			change += arr[i]
			delta += arr[i] * 2 + 1
	print(min(current + delta + 2 * (k - change), 2 * n - 1))


import sys
input = sys.stdin.readline

def print(val):
	sys.stdout.write(str(val) + '\n')

def prog():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		s = list(input().strip() + 'W')
		bounds = []
		if s[0] == 'L':
			bounds.append([1, 1, 0])
		for i in range(len(s) - 1):
			if s[i] == 'L':
				if s[i + 1] == 'L':
					bounds[-1][1] += 1
			if s[i] == 'W':
				if s[i + 1] == 'L':
					bounds.append([0, 1, i + 1])
		if s[-2] == 'L':
			bounds[-1][0] = 2
		bounds.sort()
		for i in range(len(bounds)):
			if k >= bounds[i][1]:
				k -= bounds[i][1]
				for j in range(bounds[i][2], bounds[i][2] + bounds[i][1]):
					s[j] = 'W'
			else:
				if bounds[i][0] == 1:
					for j in range(bounds[i][2] + bounds[i][1] - 1, bounds[i][2] + bounds[i][1] - 1 - k, -1):
						s[j] = 'W'
				else:
					for j in range(bounds[i][2], bounds[i][2] + k):
						s[j] = 'W'
				break
		tot = 0
		for i in range(len(s) - 1):
			tot += (s[i] == 'W') + (s[i] == 'W' and i > 0 and (s[i - 1] == 'W'))
		print(tot)
prog()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ar = list(input())
	fro = 0
	bac = 0
	li = []
	for i in range(n):
		if ar[i] == 'L':
			fro += 1
		else:
			break
	for i in range(1, n + 1):
		if ar[-i] == 'L':
			bac += 1
		else:
			break
	win = ar.count('W')
	if win == 0:
		print(max(2 * (k - 1) + 1, 0))
	elif win == 1:
		ind = ar.index('W')
		i = ind + 1
		ans = 1
		while i < n and k != 0:
			ans += 2
			i += 1
			k -= 1
		i = ind - 1
		while i >= 0 and k != 0:
			ans += 2
			i -= 1
			k -= 1
		print(ans)
	else:
		count = 0
		for i in range(fro, n - bac):
			if ar[i] == 'L':
				count += 1
			else:
				li.append(count)
				count = 0
		li.sort()
		ans = int(ar[0] == 'W')
		for i in range(1, n):
			if ar[i] == 'W':
				if ar[i - 1] == 'W':
					ans += 2
				else:
					ans += 1
		for i in li:
			if i <= k and i != 0:
				ans += 2 * i + 1
				k -= i
			elif i != 0:
				ans += 2 * k
				k = 0
		for i in [fro, bac]:
			if i <= k:
				ans += 2 * i
				k -= i
			else:
				ans += 2 * k
				k = 0
		print(ans)