import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod = 1000000007;
	static int inf = 1000000000;
	static long[] fac;
	static int[] si;
	static int n, k;
	static long[][] memo;
	static long[][] a;

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		memo = new long[n + 1][11];
		a = new long[n][6];
		for (int i = 0; i < n; i++) {
			k = sc.nextInt();
			PriorityQueue<Long> pq = new PriorityQueue<>();
			long two = 0;
			long three = 0;
			for (int j = 0; j < k; j++) {
				int x = sc.nextInt();
				if (x == 2)
					two = Math.max(two, sc.nextInt());
				else if (x == 3)
					three = Math.max(three, sc.nextInt());
				else
					pq.add(sc.nextLong());
				if (pq.size() > 3)
					pq.remove();
			}
			a[i][4] = three;
			a[i][3] = two;
			PriorityQueue<Long> pq1 = new PriorityQueue<>((op,op1)->(int)(op1-op));
			for(long t:pq)
				pq1.add(t);
			if (!pq1.isEmpty())
				a[i][2] = pq1.poll();
			if (!pq1.isEmpty())
				a[i][1] = pq1.remove();
			if (!pq1.isEmpty())
				a[i][0] = pq1.remove();
		}
	    long [][]dp=new long[n+1][11];
	    for(int i=n-1;i>=0;i--) {
	    	for(int m=0;m<10;m++) {
	    		long ans=dp[i+1][m];
	    		if (m == 9) {
	    			if(a[i][4]!=0)
	    			ans = Math.max(ans, 2 * a[i][4] + dp[i+1][m+1]);
	    			if(a[i][3]!=0)
	    			ans = Math.max(ans, 2 * a[i][3] + dp[i+1][m+1]);
	    			if(a[i][2]!=0)
	    			ans = Math.max(ans, 2 * a[i][2] + dp[i+1][m+1]);
	    			if (a[i][2] != 0 && a[i][3] != 0)
	    				ans = Math.max(ans, 2 * Math.max(a[i][2], a[i][3]) + Math.min(a[i][2], a[i][3]) + dp[i+1][(m+2)%10]);
	    			if (a[i][2] != 0 && a[i][1] != 0)
	    				ans = Math.max(ans, 2 * a[i][2] + a[i][1] + dp[i+1][(m+2)%10]);
	    			if (a[i][2] != 0 && a[i][1] != 0 && a[i][0] != 0)
	    				ans = Math.max(ans, 2 * a[i][2] + a[i][1] + a[i][0] + dp[i+1][(m+3)%10]);
	    		} else if (m == 8) {
	    			if(a[i][4]!=0)
		    			ans = Math.max(ans,  a[i][4] + dp[i+1][m+1]);
		    			if(a[i][3]!=0)
		    			ans = Math.max(ans,  a[i][3] + dp[i+1][m+1]);
		    			if(a[i][2]!=0)
		    			ans = Math.max(ans,  a[i][2] + dp[i+1][m+1]);
		    			if (a[i][2] != 0 && a[i][3] != 0)
		    				ans = Math.max(ans, 2 * Math.max(a[i][2], a[i][3]) + Math.min(a[i][2], a[i][3]) + dp[i+1][m+2]);
		    			if (a[i][2] != 0 && a[i][1] != 0)
		    				ans = Math.max(ans, 2 * a[i][2] + a[i][1] + dp[i+1][m+2]);
		    			if (a[i][2] != 0 && a[i][1] != 0 && a[i][0] != 0)
		    				ans = Math.max(ans, 2 * a[i][2] + a[i][1] + a[i][0] + dp[i+1][(m+3)%10]);
	    		} else if (m == 7) {
	    			if(a[i][4]!=0)
		    			ans = Math.max(ans,  a[i][4] + dp[i+1][m+1]);
		    			if(a[i][3]!=0)
		    			ans = Math.max(ans,  a[i][3] + dp[i+1][m+1]);
		    			if(a[i][2]!=0)
		    			ans = Math.max(ans,  a[i][2] + dp[i+1][m+1]);
		    			if (a[i][2] != 0 && a[i][3] != 0)
		    				ans = Math.max(ans,  Math.max(a[i][2], a[i][3]) + Math.min(a[i][2], a[i][3]) + dp[i+1][m+2]);
		    			if (a[i][2] != 0 && a[i][1] != 0)
		    				ans = Math.max(ans,  a[i][2] + a[i][1] + dp[i+1][m+2]);
		    			if (a[i][2] != 0 && a[i][1] != 0 && a[i][0] != 0)
		    				ans = Math.max(ans, 2 * a[i][2] + a[i][1] + a[i][0] + dp[i+1][(m+3)%10]);
	    		} else if(m<7){
	    			if(a[i][4]!=0)
		    			ans = Math.max(ans,  a[i][4] + dp[i+1][m+1]);
		    			if(a[i][3]!=0)
		    			ans = Math.max(ans,  a[i][3] + dp[i+1][m+1]);
		    			if(a[i][2]!=0)
		    			ans = Math.max(ans,  a[i][2] + dp[i+1][m+1]);
		    			if (a[i][2] != 0 && a[i][3] != 0)
		    				ans = Math.max(ans,  Math.max(a[i][2], a[i][3]) + Math.min(a[i][2], a[i][3]) + dp[i+1][m+2]);
		    			if (a[i][2] != 0 && a[i][1] != 0)
		    				ans = Math.max(ans,  a[i][2] + a[i][1] + dp[i+1][m+2]);
		    			if (a[i][2] != 0 && a[i][1] != 0 && a[i][0] != 0)
		    				ans = Math.max(ans,  a[i][2] + a[i][1] + a[i][0] + dp[i+1][(m+3)%10]);
	    		}
	    		dp[i][m]=ans;
	    	}
	    }
	    out.print(dp[0][0]);
		out.flush();
	}

	static long dp(int i, int m) {
		if (i == n)
			return 0l;
		if (memo[i][m] != -1l)
			return memo[i][m];
		long ans = 0;
		long[] ma = new long[3];
		for (int id = 0; id < 3; id++) {
				ma[id] = a[i][id];
		}
		if (m == 9) {
			if(a[i][4]!=0)
			ans = Math.max(ans, 2 * a[i][4] + dp(i + 1, (m + 1) % 10));
			if(a[i][3]!=0)
			ans = Math.max(ans, 2 * a[i][3] + dp(i + 1, (m + 1) % 10));
			if(ma[2]!=0)
			ans = Math.max(ans, 2 * ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, 2 * Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else if (m == 8) {
			if(a[i][4]!=0)
			ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
			if(a[i][3]!=0)
			ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
			if(ma[2]!=0)
			ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, 2 * Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else if (m == 7) {
			if(a[i][4]!=0)
				ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
				if(a[i][3]!=0)
				ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
				if(ma[2]!=0)
				ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else if(m<7){
			if(a[i][4]!=0)
				ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
				if(a[i][3]!=0)
				ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
				if(ma[2]!=0)
				ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		}
		return memo[i][m] = ans;
	}

	static class pair implements Comparable<pair> {
		int x;
		int y;

		pair(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public String toString() {
			return x + " " + y;
		}

		public int compareTo(pair o) {
			return y - o.y;
		}
	}

	static long inver(long x) {
		int a = (int) x;
		long e = (mod - 2);
		long res = 1;
		while (e > 0) {
			if ((e & 1) == 1) {
				// System.out.println(res*a);
				res = (int) ((1l * res * a) % mod);
			}
			a = (int) ((1l * a * a) % mod);
			e >>= 1;
		}
		// out.println(res+" "+x);
		return res % mod;
	}

	static long fac(int n) {
		if (n == 0)
			return fac[n] = 1;
		if (n == 1)
			return fac[n] = 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			fac[i] = ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class sol {
		boolean st;
		int l;
		int r;
		char s;

		sol(boolean st, int l, int r, char s) {
			this.st = st;
			this.l = l;
			this.r = r;
			this.s = s;
		}

		public String toString() {
			return st + " " + l + " " + r + " " + s;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod = 1000000007;
	static int inf = 1000000000;
	static long[] fac;
	static int[] si;
	static int n, k;
	static long[][] memo;
	static long[][] a;

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		memo = new long[n + 1][11];
		a = new long[n][6];
		for (int i = 0; i < n; i++) {
			k = sc.nextInt();
			PriorityQueue<Long> pq = new PriorityQueue<>();
			long two = 0;
			long three = 0;
			for (int j = 0; j < k; j++) {
				int x = sc.nextInt();
				if (x == 2)
					two = Math.max(two, sc.nextInt());
				else if (x == 3)
					three = Math.max(three, sc.nextInt());
				else
					pq.add(sc.nextLong());
				if (pq.size() > 3)
					pq.remove();
			}
			a[i][4] = three;
			a[i][3] = two;
			PriorityQueue<Long> pq1 = new PriorityQueue<>((op,op1)->(int)(op1-op));
			for(long t:pq)
				pq1.add(t);
			if (!pq1.isEmpty())
				a[i][2] = pq1.poll();
			if (!pq1.isEmpty())
				a[i][1] = pq1.remove();
			if (!pq1.isEmpty())
				a[i][0] = pq1.remove();
		}
		for (long[] h : memo)
			Arrays.fill(h, -1);
		out.println(dp(0, 0));
		out.flush();
	}

	static long dp(int i, int m) {
		if (i == n)
			return 0;
		if (memo[i][m] != -1l)
			return memo[i][m];
		long ans = 0;
		long[] ma = new long[3];
		for (int id = 0; id < 3; id++) {
				ma[id] = a[i][id];
		}
	//	Arrays.sort(ma);
	//	ans = Math.max(ans, dp(i + 1, (m) % 10));
		if (m == 9) {
			ans = Math.max(ans, 2 * a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, 2 * a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, 2 * ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, 2 * Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else if (m == 8) {
			ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, 2 * Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else if (m == 7) {
			ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else {
			ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		}
		return memo[i][m] = ans;
	}

	static class pair implements Comparable<pair> {
		int x;
		int y;

		pair(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public String toString() {
			return x + " " + y;
		}

		public int compareTo(pair o) {
			return y - o.y;
		}
	}

	static long inver(long x) {
		int a = (int) x;
		long e = (mod - 2);
		long res = 1;
		while (e > 0) {
			if ((e & 1) == 1) {
				// System.out.println(res*a);
				res = (int) ((1l * res * a) % mod);
			}
			a = (int) ((1l * a * a) % mod);
			e >>= 1;
		}
		// out.println(res+" "+x);
		return res % mod;
	}

	static long fac(int n) {
		if (n == 0)
			return fac[n] = 1;
		if (n == 1)
			return fac[n] = 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			fac[i] = ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class sol {
		boolean st;
		int l;
		int r;
		char s;

		sol(boolean st, int l, int r, char s) {
			this.st = st;
			this.l = l;
			this.r = r;
			this.s = s;
		}

		public String toString() {
			return st + " " + l + " " + r + " " + s;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


import java.io.*;
import java.util.*;

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static long mod = 1000000007;
	static int inf = 1000000000;
	static long[] fac;
	static int[] si;
	static int n, k;
	static long[][] memo;
	static long[][] a;

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		memo = new long[n + 1][11];
		a = new long[n][6];
		for (int i = 0; i < n; i++) {
			k = sc.nextInt();
			PriorityQueue<Long> pq = new PriorityQueue<>();
			long two = 0;
			long three = 0;
			for (int j = 0; j < k; j++) {
				int x = sc.nextInt();
				if (x == 2)
					two = Math.max(two, sc.nextInt());
				else if (x == 3)
					three = Math.max(three, sc.nextInt());
				else
					pq.add(sc.nextLong());
				if (pq.size() > 3)
					pq.remove();
			}
			a[i][4] = three;
			a[i][3] = two;
			if (!pq.isEmpty())
				a[i][0] = pq.remove();
			if (!pq.isEmpty())
				a[i][1] = pq.remove();
			if (!pq.isEmpty())
				a[i][2] = pq.remove();
		}
		for (long[] h : memo)
			Arrays.fill(h, -1);
		out.println(dp(0, 0));
		out.flush();
	}

	static long dp(int i, int m) {
		if (i == n)
			return 0;
		if (memo[i][m] != -1l)
			return memo[i][m];
		long ans = 0;
		Long[] ma = new Long[3];
		for (int id = 0; id < 5; id++) {
			if (id < 3) {
				ma[id] = a[i][id];
			}
		}
		Arrays.sort(ma);
		ans = Math.max(ans, dp(i + 1, (m) % 10));
		if (m == 9) {
			ans = Math.max(ans, 2 * a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, 2 * a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, 2 * ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, 2 * Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else if (m == 8) {
			ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, 2 * Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else if (m == 7) {
			ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, 2 * ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		} else {
			ans = Math.max(ans, a[i][4] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, a[i][3] + dp(i + 1, (m + 1) % 10));
			ans = Math.max(ans, ma[2] + dp(i + 1, (m + 1) % 10));
			if (ma[2] != 0 && a[i][3] != 0)
				ans = Math.max(ans, Math.max(ma[2], a[i][3]) + Math.min(ma[2], a[i][3]) + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + dp(i + 1, (m + 2) % 10));
			if (ma[2] != 0 && ma[1] != 0 && ma[0] != 0)
				ans = Math.max(ans, ma[2] + ma[1] + ma[0] + dp(i + 1, (m + 3) % 10));
		}
		return memo[i][m] = ans;
	}

	static class pair implements Comparable<pair> {
		int x;
		int y;

		pair(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public String toString() {
			return x + " " + y;
		}

		public int compareTo(pair o) {
			return y - o.y;
		}
	}

	static long inver(long x) {
		int a = (int) x;
		long e = (mod - 2);
		long res = 1;
		while (e > 0) {
			if ((e & 1) == 1) {
				// System.out.println(res*a);
				res = (int) ((1l * res * a) % mod);
			}
			a = (int) ((1l * a * a) % mod);
			e >>= 1;
		}
		// out.println(res+" "+x);
		return res % mod;
	}

	static long fac(int n) {
		if (n == 0)
			return fac[n] = 1;
		if (n == 1)
			return fac[n] = 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			fac[i] = ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class sol {
		boolean st;
		int l;
		int r;
		char s;

		sol(boolean st, int l, int r, char s) {
			this.st = st;
			this.l = l;
			this.r = r;
			this.s = s;
		}

		public String toString() {
			return st + " " + l + " " + r + " " + s;
		}
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		void combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


t = int(input())
for _ in range(t):
    n,k = list(map(int, input().split()))
    string = list(input())
    # eliminate boarder
    lis = []
    i = 0
    j = n-1
    counter = 0
    for _i_ in string:
        if _i_ != 'W':
            counter+=1
            i+=1
        else:
            break

    b1 = (counter , i-1)
    #print(b1)
    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':
            while string[i] == 'L':
                counter+=1
                i+=1
            lis.append((counter , i-1))
        else:
            i+=1
    lis.sort()
    lis.append(b1)
    lis.append(b2)
    #print(lis)
    for i in lis:
        count = i[0]
        j = i[1]
        while k>0 and string[j]!='W':
            string[j] ='W'
            j-=1
            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 _ in range(t):
    n,k = list(map(int, input().split()))
    string = list(input())
    # eliminate boarder
    lis = []
    i = 0
    j = n-1
    counter = 0
    for _i_ in string:
        if _i_ != 'W':
            counter+=1
            i+=1
        else:
            break
    b1 = (counter , 0)
    #print(b1)
    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()
    lis.append(b1)
    lis.append(b2)
    #print(lis)
    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

    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 _ in range(t):
    n,k = list(map(int, input().split()))
    string = list(input())
    # eliminate boarder
    lis = []
    i = 0
    j = n-1
    counter = 0
    for _i_ in string:
        if _i_ != 'W':
            counter+=1
            i+=1
        else:
            break
    b1 = (counter , 0)
    #print(b1)
    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()
    lis.append(b1)
    lis.append(b2)
    #print(lis)
    for i in lis:
        count = i[0]
        j = i[1]
        while k>0 and string[j]!='W':
            string[j] ='W'
            j+=1
            k-=1
            if j>=n:
                break
    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 _ in range(t):
    n,k = list(map(int, input().split()))
    string = list(input())
    # eliminate boarder
    lis = []
    i = 0
    j = n-1
    counter = 0
    for _i_ in string:
        if _i_ != 'W':
            counter+=1
            i+=1
        else:
            break
    b1 = (counter , 0)
    #print(b1)
    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()
    #lis.append(b1)
    #lis.append(b2)
    #print(lis)
    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())
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
            else:
                if i!=start:
                    if arr[i-1]=="W":point+=2
                    else:point+=1
                else:point+=1

    for score,count in dict.items():
        if k>0:
            if k>=score*count:
                k-=score*count
                point+=score*count*2+count
            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
        else:
            if k>=left:point+=left*2-1 ;k-=left
            else:point+=k*2-1 ;k-=k

    print(point)


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
            else:
                if 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
        else:
            if k>=left:point+=left*2-1 ;k-=left
            else:point+=k*2-1 ;k-=k

    print(point)


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
            else:
                if i!=start:
                    if arr[i-1]=="W":point+=2
                    else:point+=1
                else:point+=1

    for score,count in reversed(dict.items()):
        if k>0:
            if k>=score*count:
                k-=score*count
                point+=score*count*2+count
            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
        else:
            if k>=left:point+=left*2-1 ;k-=left
            else:point+=k*2-1 ;k-=k

    print(point)


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()
    # print(bb)
    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

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

from heapq import *

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=SI()
    cc,aa=RLE(s)
    if cc.count("W")<2:
        a=s.count("W")
        print(max(0,min(k+a,n)*2-1))
        continue
    if cc[-1]=="L":aa.pop()
    if cc[0]=="L":aa=aa[1:]

    ans=0
    bb=[]
    for i,a in enumerate(aa):
        if i&1:bb.append(a)
        else:ans+=2*a-1
    bb.sort()
    # print(bb)
    for b in bb:
        if b>k:break
        ans+=2*b+1
        k-=b
    ans+=2*k
    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:
				# print('yes',2*(final-sum1))
				sum2 = sum2 + (2*(final-sum1))
				sum1 = sum1 + (final-sum1)
				break
			# print(i,sum2,final-sum1)
		print(sum2)
	else:
		if s[0]=='L':
			print(max(0,2*final-1))
		else:
			print(earlier_count)


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))


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 17:41:36 2020

@author: 章斯岚
"""

for i in range(int(input())):
    n,k=map(int,input().split())
    l=input()
    point=0
    temp=1
    if l.count('L')<=k:
        point=2*n-1
    elif 'W' not in l:
        point=max(2*k-1,0)
    else:
        for i in l:
            if i=='W':
                point+=temp
                temp=2
            else:
                temp=1
        i=1
        while i<=k:
            m=min(l.count('W'+'L'*i+'W'),k//i)
            point+=(1+i*2)*m
            k-=m*i
            i+=1
        point+=2*k
    print(point)


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 17:41:36 2020

@author: 章斯岚
"""

for i in range(int(input())):
    n,k=map(int,input().split())
    l=input()
    point=0
    temp=1
    if l.count('L')<=k:
        point=2*n-1
    else:
        for i in l:
            if i=='W':
                point+=temp
                temp=2
            else:
                temp=1
        i=1
        while i<=k:
            m=min(l.count('W'+'L'*i+'W'),k//i)
            point+=(1+i*2)*m
            k-=m*i
            i+=1
        point+=2*k
    print(point)


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 20:10:01 2020

@author: 章斯岚
"""
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)


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 17:41:36 2020

@author: 章斯岚
"""

for i in range(int(input())):
    n,k=map(int,input().split())
    l=input()
    point=0
    temp=1
    if l.count('L')<=k:
        point=2*n-1
    elif l.count('L')==n:
        point=2*k-1
    else:
        for i in l:
            if i=='W':
                point+=temp
                temp=2
            else:
                temp=1
        i=1
        while i<=k:
            m=min(l.count('W'+'L'*i+'W'),k//i)
            point+=(1+i*2)*m
            k-=m*i
            i+=1
        point+=2*k
    print(point)


import sys
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(max(2*(k+l)-1 , 0))
  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
    print(ans)
for i in range(t):
  n , k = map(int,input().split())
  s = list(str(input()))
  answer(n,k,s)


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)


import sys
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
    print(ans)
for i in range(t):
  n , k = map(int,input().split())
  s = list(str(input()))
  answer(n,k,s)


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
    ##print("original" , score)
    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)
    ##print(lstl)
    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)


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
    ##print("original" , score)
    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)
    ##print(lstl)
    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)


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
		# print(initial_score)
		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()
		# print(mid_los_ar)
		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

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:
		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
		# print(initial_score)
		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()
		# print(mid_los_ar)
		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)


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


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)


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


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=k
 while a and a[0]<=r:r-=a.pop(0)
 print((2*min(n,s.count('W')+k)-len(a)or 1)-1)


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


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


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()
	#print(mas)
	#print(kol)
	#print(ans)
	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
		#print("A", gh)
		for i in ans:
			z = i
			#print(k, z)
			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
		#print("B", gh)
		dz = sum(mas) + kz
		dz = n - dz
		gh += min(k, dz) * 2
		print(gh)


def score(s):
    rv=0
    for z in range(len(s)):
        if s[z]=='W':
            if z==0:
                rv+=1
            else:
                if 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
                else:
                    if 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 score(s):
    rv=0
    for z in range(len(s)):
        if s[z]=='W':
            if z==0:
                rv+=1
            else:
                if s[z-1]=='W':
                    rv+=2
                else:
                    rv+=1
    return rv
for _ in range(int(input())):
    n,k=map(int,input().split())
    s=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
                else:
                    if 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=s[:x+z[1]]+"W"+s[x+z[1]+1:]
            while k and eidx+1<n:
                s=s[:eidx+1]+"W"+s[eidx+2:]
                eidx+=1
                k-=1
            while k and iidx-1>-1:
                s=s[:iidx-1]+"W"+s[iidx:]
                iidx-=1
                k-=1
            print(score(s))


def solve():

  n,k = map(int,input().split())
  s = list(input())
  # dp = defaultdict(int)
  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]
          # print(b,c)
          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()


def solve():

  n,k = map(int,input().split())
  s = list(input())
  dp = defaultdict(int)
  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]
          # print(b,c)
          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()


#!/usr/bin/python3

ns = lambda: input()
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

"B. Chess Cheater"
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)
    # print(w)
    # print(l)
    # print(ll)
    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
    # print(ll,z)
    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)


#!/usr/bin/python3

ns = lambda: input()
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

"B. Chess Cheater"
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)
    # print(w)
    # print(l)
    # print(ll)
    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)
    if l[0]!=0:
        t=ll.pop(0)
        z.append(t)
    if l[-1]!=0:
        t=ll.pop(-1)
        z.append(t)
    ll.sort()
    su=0
    ind=0
    # print(ll,z)
    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)


#!/usr/bin/python3

ns = lambda: input()
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

"B. Chess Cheater"
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)
    # print(w)
    # print(l)
    # print(ll)
    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
    # print(ll,z)
    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)


#!/usr/bin/python3

ns = lambda: input()
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

"B. Chess Cheater"
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)
    # print(w)
    # print(l)
    # print(ll)
    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:
        t=ll.pop(0)
        z.append(t)
    if l[-1]!=0:
        t=ll.pop(-1)
        z.append(t)
    ll.sort()
    su=0
    ind=0
    # print(ll,z)
    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)


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


t = int(input())
for _ in range(0,t):
    n,k = [int(x) for x in input().split()]
    a = sorted(map(len,input().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)


t = int(input())

for _ in range(t):
    n, k = input().split()
    n, k = int(n), int(k)

    s = input()
    ind = []

    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)

##    print(score)
##    print(gaps)

    j = 0
    while (j < len(gaps)) and (k >= gaps[j] - 1):
        k -= gaps[j] - 1
        score += 2*gaps[j] - 1
        j += 1

##    print('k: ', k, 'score:', score)

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


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)

##    print(score)
##    print(gaps)

    j = 0
    while (j < len(gaps)) and (k >= gaps[j] - 1):
        k -= gaps[j] - 1
        score += 2*gaps[j] - 1
        j += 1

##    print('k: ', k, 'score:', score)

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


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)


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)


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:
            if(j==n-1):
                b.append(j+100000)
            if(j==0):
                b.append(-1)
            q=0
    g=n-cw
    if(g<=m):
        s=1+2*(n-1)
    if(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:
                s=s+2*(m)
                break
    print(s)


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(g<=m):
        s=1+2*(n-1)
    if(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)


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)


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:
        i = 1
        while k > 0 and i < n - 1:
            if a[i] == 'L' and a[i - 1] == 'W' and a[i + 1] == 'W':
                k = k - 1
                a[i] = 'W'
                if k == 0:
                    break
            i = i + 1
        if k == 0:
            f = 0
            ans = 0
            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)
        elif k > 0:
            while k > 0:
                i = 0
                while i < n:
                    if a[i] == 'L':
                        if i != 0 and i != n - 1:

                            if a[i + 1] == 'W' or (a[i - 1] == 'W'):

                            a[i] = 'W'
                            k = k - 1
                            if k == 0:
                                break

                        if i == 0:
                            if a[i + 1] == 'W':
                                a[i] ='W'
                                k = k - 1
                                if k == 0:
                                    break
                        if i == n - 1:
                            if a[i - 1] == 'W':
                                a[i] == 'W'
                                k = k - 1
                                if k == 0:
                                    break

                    i = i + 1
            ans = 0
            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)


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:
        i = 1
        while k > 0 and i < n - 1:
            if a[i] == 'L' and a[i - 1] == 'W' and a[i + 1] == 'W':
                k = k - 1
                a[i] = 'W'
                if k == 0:
                    break
            i = i + 1
        if k == 0:
            f = 0
            ans = 0
            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)
        elif k > 0:
            while k > 0:
                i = 0
                while i < n:
                    if a[i] == 'L':
                        if i != 0 and i != n - 1:

                            if a[i + 1] == 'W' or (a[i - 1] == 'W'):
                                a[i] = 'W'
                                k = k - 1
                                if k == 0:
                                    break

                        if i == 0:
                            if a[i + 1] == 'W':
                                a[i] ='W'
                                k = k - 1
                                if k == 0:
                                    break
                        if i == n - 1:
                            if a[i - 1] == 'W':
                                a[i] == 'W'
                                k = k - 1
                                if k == 0:
                                    break

                    i = i + 1
            ans = 0
            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)


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
            else:
                if 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)


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:
        i=1
        while k>0 and i<n-1:
            if a[i]=='L' and a[i-1]=='W' and a[i+1]=='W':
                k=k-1
                a[i]='W'
                if k==0:
                    break
            i=i+1
        if k==0:
            f=0
            ans=0
            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)
        elif k>0:
            while k>0:
                i=0
                while i<n-1:
                    if a[i]=='L':
                        if a[i+1]=='W':
                            a[i]='W'
                            k=k-1
                            if k==0:
                                break
                            if a.count('L')==1 and a[n-1]=='L' and k==1:
                                a[n-1]='W'
                                k=k-1
                    i=i+1
            ans=0
            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
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(lsum)
        # print(n)
        # print(endloss)
        # print(startloss)
        # print(starts)
        print((n-lsum)*2-starts)


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!=0:
                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)


# only gravity will pull me down

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()
		#print(mp)
		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 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 # Ls at beginning
    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
        else:
            if k > 0:
                ans += 2 * k
                k = 0
    ans += 2 * min(k, b+e)
    print(ans)


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)


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)


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


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


import sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
    n,k=map(int,input().split())
    s=input()
    l=list(s)
    i=0
    for i in range(1,n-1):
            if(k>0):
                if(l[i]=='L' and l[i-1]=='W' and l[i+1]=='W'):
                    k-=1
                    l[i]='W'
            else:
                break
    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
    for i in range(1,n-1):
            if(k>0):
                if(l[i]=='L' and l[i-1]=='W' and l[i+1]=='W'):
                    print(i)
                    k-=1
                    l[i]='W'
            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
    if(k>0):
        for i in range(1,n-1):
            if(k>0):
                if(l[i]=='L' and l[i-1]=='W' and l[i+1]=='W'):
                    k-=1
                    l[i]='W'
            else:
                break
    if(k>0):
        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)


t=int(input())
for _ in range(t):
    n,k=map(int,input().split())
    s=input()
    l=list(s)
    #print(l)
    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
            temp.append([j-i-1,i+1,j])
            i=j
        else:
            i+=1
    temp.sort()
    #print(temp)
    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)


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)


def solve():
	n,k=map(int,input().split())
	#print(n,k)
	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()


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)


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+=min(k,1)
    else:
        sum+=2*min(k,count)

    # print(ls)
    print(sum)


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(ls)
    print(sum)


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+=2*min(k,n)-1
    else:
        sum+=2*min(k,count)

    # print(ls)
    print(sum)


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()
    le=len(w)
    while(len(w)>0):
        if(k==0):
            break
        if(w[0]==0):
            w=w[1:]
            le-=1
            if(le==0):
                break
        if(w[0]==1):
            ans+=3
            w[0]=0
            k-=1
            cl-=1
        else:
            w[0]-=1
            ans+=2
            k-=1
            cl-=1

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


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
        else:
            if(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)


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)


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
            #print(tail)
        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)