solution
stringlengths 11
983k
| difficulty
int64 0
21
| language
stringclasses 2
values |
---|---|---|
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict,deque,Counter
from bisect import *
from math import sqrt,pi,ceil,log,inf
from itertools import permutations
from copy import deepcopy
from sys import setrecursionlimit
def main():
for _ in range(int(input())):
n,k=map(int,input().split())
a=list(input().rstrip())
b=[]
i=0
while i<n:
if a[i]=="L":
j=i+1
while j<n and a[j]=="L":
j+=1
b.append([i,j-1])
i=j
i+=1
b.sort(key=lambda x:(x[1]-x[0])+(0 if (x[0]!=0 and x[1]!=n-1) else 10**5))
for i in range(len(b)):
for j in range(b[i][0] if b[i][0]!=0 else b[i][1],b[i][1]+1 if b[i][0]!=0 else b[i][0]-1,1 if b[i][0]!=0 else -1):
if k==0:
break
a[j]="W"
k-=1
if k==0:
break
ans=int(a[0]=="W")
for i in range(1,n):
if a[i-1]=="W" and a[i]=="W":
ans+=2
elif a[i]=="W":
ans+=1
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main() | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
const double PI = acos(-1.0);
const long long int mod = 1e9 + 7;
const int MAXN = 1e6 + 5;
void cp() {
int n, k;
string s;
cin >> n >> k >> s;
vector<pair<int, int> > group;
int l = 0, r = 0;
while (l < n) {
while (l < n && s[l] == 'L') l++;
if (l >= n) break;
r = l;
while (r + 1 < n && s[r + 1] == 'W') r++;
group.push_back({l, r});
l = r + 1;
}
vector<pair<int, int> > diff;
for (int i = 0; i < ((int)group.size()) - 1; i++) {
int d = group[i + 1].first - group[i].second - 1;
diff.push_back({d, i});
}
sort(diff.rbegin(), diff.rend());
while (k > 0 && !diff.empty()) {
pair<int, int> last = diff.back();
diff.pop_back();
int can = min(last.first, k);
k -= can;
for (int i = group[last.second].second + 1;
i < group[last.second + 1].first && can > 0; i++, can--)
s[i] = 'W';
}
if (k > 0) {
int pos = -2;
for (int i = 0; i < n; i++)
if (s[i] == 'W') pos = i;
pos++;
if (pos >= 0 && pos < n)
for (int i = pos; i < n && k > 0; i++)
if (s[i] == 'L') s[i] = 'W', k--;
}
if (k > 0 && s[0] == 'L') {
int pos = n;
for (int i = 0; i < n && pos == n; i++)
if (s[i] == 'W') pos = i;
pos--;
if (pos >= 0) {
for (int i = pos; i >= 0 && k > 0; i--)
if (s[i] == 'L') s[i] = 'W', k--;
}
}
int score = 0;
for (int i = 0; i < n; i++) {
score += (s[i] == 'W');
if (i - 1 >= 0 && s[i] == 'W' && s[i - 1] == 'W') score++;
}
cout << score << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
;
int t;
t = 1;
cin >> t;
while (t--) {
cp();
}
return 0;
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
mt19937 rnf(2106);
const int N = 100005;
int n, k;
char a[N];
void solv() {
scanf("%d%d", &n, &k);
scanf("%s", a);
vector<int> v;
bool z = false;
int q = 0;
for (int i = 0; i < n; ++i) {
if (a[i] == 'L')
++q;
else {
if (z) v.push_back(q);
q = 0;
z = true;
}
}
q = 0;
for (int i = 0; i < n; ++i) {
if (a[i] == 'W') ++q;
}
if (q + k >= n) {
printf("%d\n", n * 2 - 1);
return;
}
if (q == 0) {
printf("%d\n", max(0, k * 2 - 1));
return;
}
int ans = q * 2;
for (int i = 0; i < n; ++i) {
if (a[i] == 'W' && (i == 0 || a[i - 1] == 'L')) --ans;
}
sort((v).begin(), (v).end());
for (int i = 0; i < ((int)(v).size()); ++i) {
if (v[i] == 0) continue;
if (k >= v[i]) {
k -= v[i];
ans += v[i] * 2;
++ans;
} else
break;
}
ans += k * 2;
printf("%d\n", ans);
}
int main() {
int tt;
scanf("%d", &tt);
while (tt--) solv();
return 0;
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
void sol() {
long long n, k;
cin >> n >> k;
string s;
cin >> s;
long long w = 0;
for (auto el : s) {
if (el == 'W') {
w++;
}
}
vector<long long> rofl;
for (long long i = 0; i < n; i++) {
if (s[i] == 'W') {
rofl.push_back(i);
}
}
vector<pair<long long, long long>> kek;
for (long long i = 1; i < (long long)rofl.size(); i++) {
long long left = rofl[i - 1], right = rofl[i];
kek.emplace_back(right - left + 1, left);
}
sort(kek.begin(), kek.end());
for (auto pp : kek) {
long long len = pp.first, l = pp.second;
for (long long i = l; i < l + len; i++) {
if (k > 0 && s[i] == 'L') {
s[i] = 'W';
k--;
}
}
}
if (rofl.empty()) {
rofl.push_back(0);
}
for (long long i = rofl.back(); i < n; i++) {
if (k > 0 && s[i] == 'L') {
k--;
s[i] = 'W';
}
}
for (long long i = rofl.back(); i >= 0; i--) {
if (k > 0 && s[i] == 'L') {
k--;
s[i] = 'W';
}
}
long long ans = 0;
for (long long i = 0; i < n; i++) {
if (s[i] == 'W') {
if (i == 0 || s[i - 1] == 'L') {
ans++;
} else {
ans += 2;
}
}
}
cout << ans << '\n';
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
long long t = 1;
cin >> t;
while (t--) {
sol();
}
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
const long long INF = 2147483647;
const long long MOD = 1000000007;
const long long mod = 998244353;
const long double eps = 1e-12;
long long n, k;
char str[100001];
long long res;
long long lcnt;
vector<long long> v;
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long T;
cin >> T;
while (T--) {
cin >> n >> k;
cin >> str;
bool flag = 1;
for (long long i = 0; i < n; i++) {
if (str[i] == 'W') {
flag = 0;
}
}
if (flag == 1) {
if (k == 0) {
cout << 0 << endl;
} else {
cout << 2 * k - 1 << endl;
}
continue;
}
v.clear();
res = 0;
lcnt = 0;
if (str[0] == 'W') {
res++;
} else {
lcnt++;
}
for (long long i = 1; i < n; i++) {
if (str[i] == 'W') {
res += (str[i - 1] == 'W') ? 2 : 1;
} else {
lcnt++;
}
}
long long prev = -INF;
for (long long i = 0; i < n; i++) {
if (str[i] == 'W') {
if (i - prev - 1 > 0 and prev != -INF) {
v.push_back(i - prev - 1);
}
prev = i;
}
}
sort(v.begin(), v.end());
for (long long i = 0; i < v.size(); i++) {
if (k >= v[i]) {
k -= v[i];
res += v[i] * 2 + 1;
lcnt -= v[i];
} else {
break;
}
}
res += 2 * min(k, lcnt);
cout << res << endl;
}
return 0;
}
| 8 | CPP |
from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
L=lambda:list(R())
P=lambda x:stdout.write(x)
lcm=lambda x,y:(x*y)//gcd(x,y)
hg=lambda x,y:((y+x-1)//x)*x
pw=lambda x:1 if x==1 else 1+pw(x//2)
chk=lambda x:chk(x//2) if not x%2 else True if x==1 else False
sm=lambda x:(x**2+x)//2
N=10**9+7
for _ in range(I()):
n,k=R()
a=[]
p=0
j=0
ans=0
for i in S():
j+=1
if i=='W':
if not p:
p=j
ans+=1
else:
if j-p-1:
a+=j-p-1,
ans+=1
else:ans+=2
p=j
if not p:print(max(0,k*2-1));continue
a.sort(reverse=True)
while a and k:
p=a.pop()
if p<=k:
ans+=p*2+1
k-=p
else:
ans+=k*2
k=0
break
print(min(n*2-1,ans+k*2)) | 8 | PYTHON3 |
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
s = input()
if all(i == "L" for i in s):
print(max(0, 2 * k - 1))
continue
f = False
if s[0] == "L":
f = True
cur = s[0]
l = []
cnt = 1
f2 = True
score = 0
for i in range(1, n):
if cur == s[i]:
cnt += 1
else:
if f2:
if f:
l.append((cnt, 2 * cnt))
else:
score += cnt * 2 - 1
f2 = False
else:
if cur == "W":
score += cnt * 2 - 1
else:
l.append((cnt, 2 * cnt + 1))
cnt = 1
cur = s[i]
if s[-1] == "W":
score += 2 * cnt - 1
else:
if f2:
l.append((cnt, 2 * cnt - 1))
else:
l.append((cnt, cnt * 2))
l.sort(key=lambda x:x[1] / x[0], reverse=True)
cnt = s.count("L")
for i, j in l:
if k - i < 0:
continue
else:
score += j
k -= i
cnt -= i
print(score + 2 * min(k, cnt)) | 8 | PYTHON3 |
#include <bits/stdc++.h>
int main() {
int t;
std::cin >> t;
for (int p = 0; p < t; p++) {
int n;
int k;
std::cin >> n >> k;
std::string word;
std::cin >> word;
std::vector<char> a(word.begin(), word.end());
std::vector<int> values;
bool left = false;
bool right = false;
if (a[0] == 'L') {
left = true;
}
if (a[a.size() - 1] == 'L') {
right = true;
}
int local = 0;
for (int i = 0; i < a.size(); i++) {
if (a[i] == 'L') {
local++;
}
if (a[i] == 'W' && local != 0) {
values.push_back(local);
local = 0;
}
}
if (local != 0) {
values.push_back(local);
local = 0;
}
int m = 0;
std::vector<int> b;
if (!left && !right) {
b = values;
std::sort(b.begin(), b.end());
}
if (left && !right) {
b = values;
b[0] = 3000000;
std::sort(b.begin(), b.end());
}
if (!left && right) {
b = values;
b.pop_back();
std::sort(b.begin(), b.end());
}
if (left && right) {
b = values;
b.pop_back();
b[0] = 3000000;
std::sort(b.begin(), b.end());
}
int sum = 0;
for (int j = 0; j < b.size() && (sum + b[j] <= k); j++) {
sum += b[j];
m++;
}
int points = 0;
for (int i = 0; i < a.size() - 1; i++) {
if (a[i] == 'W') {
points++;
}
if (a[i] == 'W' && a[i + 1] == 'W') {
points++;
}
}
if (!right) {
points++;
}
points += m;
int suml = 0;
for (int i = 0; i < values.size(); i++) {
suml += values[i];
}
if (suml == a.size() && k > 0) {
points += 2 * std::min(suml, k);
points--;
} else {
points += 2 * std::min(suml, k);
}
std::cout << points << std::endl;
}
return 0;
}
| 8 | CPP |
def solve():
n,k=map(int,input().split())
s=input()[:n]
z=s.count('W')
leftL=n-z
if z==0:
if k!=0:
print(1+2*(k-1))
else:
print(0)
else:
total=0
for i in range(n):
if s[i]=='W':
if (i-1)>=0:
if s[i-1]=='W':
total+=2
else:
total+=1
else:
total+=1
cont_seg=[]
fir,sec=-1,-1
for i in range(n):
if s[i]=='W':
if fir==-1:
fir=i
else:
sec=i
if fir!=-1 and sec!=-1:
temp=sec-fir-1
if temp>0:
cont_seg.append(temp)
fir=sec
cont_seg.sort()
for i in cont_seg:
if i<=k:
total+=1+i*2
k-=i
leftL-=i
if leftL!=0 and k!=0:
if leftL<=k:
total+=leftL*2
elif leftL>k:
total+=k*2
print(total)
if __name__ == "__main__":
for _ in range(int(input())):
solve() | 8 | PYTHON3 |
# import sys; input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10**7)
from collections import defaultdict
mod = 10 ** 9 + 7; INF = float("inf")
def getlist():
return list(map(int, input().split()))
def inverse(N, mod):
return (pow(N, mod - 2, mod))
def main():
T = int(input())
for _ in range(T):
N, K = getlist()
s = list(input())
K2 = K
num = s.count("W")
if num == 0:
ans = 2 * min(N, K) - 1
print(max(ans, 0))
else:
Lis = []
cnt = 0
for i in s:
if i == "L":
cnt += 1
else:
if cnt != 0:
Lis.append(cnt)
cnt = 0
if cnt != 0:
Lis.append(cnt)
Lis2 = []
M = len(Lis)
seg = M - 1
cnt2 = 0
S, G = 0, M
if s[0] == "W":
seg += 1
else:
S += 1
if s[-1] == "W":
seg += 1
else:
G -= 1
# print(Lis)
# print(seg, cnt2)
for i in range(S, G):
Lis2.append(Lis[i])
Lis2.sort()
# print(Lis2)
M2 = len(Lis2)
for i in range(M2):
if K >= Lis2[i]:
seg -= 1
K -= Lis2[i]
else:
break
ans = 2 * min(N, num + K2) - seg
print(ans)
if __name__ == '__main__':
main() | 8 | PYTHON3 |
def solve():
n, k = map(int, input().split())
A = input()
segs = []
s, t = 0, 0
while s < n and A[s] == 'L':
s += 1
head = (0, s)
nn = n
while nn >= 1 and A[nn - 1] == 'L':
nn -= 1
tail = (nn, n)
while s < nn:
if A[s] == 'W':
s += 1
continue
t = s
while t < nn and A[t] == 'L':
t += 1
segs.append((s, t))
s = t
segs.sort(key=lambda x: x[1] - x[0])
B = list(A)
for (s, t) in segs:
if k <= 0:
break
w = min(t - s, k)
B[s:s+w] = 'W' * w
k -= w
if k > 0 and tail[0] != n:
s, t = tail
w = min(t - s, k)
B[s:s+w] = 'W' * w
k -= w
if k > 0 and head[1] > 0:
s, t = head
w = min(t - s, k)
B[t - w: t] = 'W' * w
k -= w
score = 0
for i in range(n):
if i >= 1 and B[i - 1] == 'W' and B[i] == 'W':
score += 2
continue
if B[i] == 'W':
score += 1
continue
return score
TC = int(input())
for _ in range(TC):
print(solve())
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int n, k;
string s;
int solve() {
vector<int> holes;
int cur = 0;
int tt = 0;
bool start = false;
int iscore = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') {
if (i > 0 && s[i - 1] == 'W')
iscore += 2;
else
iscore++;
if (!start) {
start = true;
tt = cur;
cur = 0;
continue;
}
if (cur > 0) {
holes.push_back(cur);
tt += cur;
cur = 0;
}
} else
cur++;
}
tt += cur;
sort(holes.begin(), holes.end());
int ct = 0, dscore = 0;
for (int i = 0; i < holes.size(); i++) {
if (k >= holes[i]) {
dscore += holes[i] * 2 + 1;
k -= holes[i];
tt -= holes[i];
} else
break;
}
dscore += 2 * min(k, tt);
if (!start && dscore > 0) dscore--;
return iscore + dscore;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int t;
cin >> t;
for (int ti = 0; ti < t; ti++) {
cin >> n >> k;
cin >> s;
cout << solve() << "\n";
}
}
| 8 | CPP |
import itertools
def remove_beginning(lst, bad):
idx = 0
while lst[idx] == bad:
idx += 1
if len(lst) == idx:
break
return idx
def solve():
n, k = [int(x) for x in input().strip().split()]
game_scores = list(input().strip())
win, lose = 'W', 'L'
first_good_pos = remove_beginning(game_scores, lose)
first_range = first_good_pos
game_scores = game_scores[first_good_pos:]
# print(f'Games after removing from head {game_scores}')
game_scores.reverse()
if not game_scores:
return max(2 * min(k, first_range) - 1, 0)
last_good_pos = remove_beginning(game_scores, lose)
last_range = last_good_pos
game_scores = game_scores[last_good_pos:]
game_scores.reverse()
# print(f'Games after removing from tail {game_scores}, {last_range}')
assignable_points_from_list_ends = first_range + last_range
lose_lengths = []
for key, group in itertools.groupby(game_scores):
lose_lengths.append([key, len(list(group))])
# print(lose_lengths)
initial_points = sum(map(lambda t: 0 if t[0] == lose else 2 * t[1] - 1, lose_lengths))
# print(f'Initial points {initial_points}. Assignable points from bounds {assignable_points_from_list_ends}')
lose_lengths = list(filter(lambda t: t > 0, map(lambda t: 0 if t[0] == win else t[1], lose_lengths)))
if n == 1:
if game_scores[0] == win:
return 1
return 1 if (k == 1) else 0
# print(lose_lengths)
lose_lengths.sort()
for l in lose_lengths:
if k >= l:
k, initial_points = k - l, initial_points + 2 * (l - 1) + 3
else:
k, initial_points = 0, initial_points + 2 * k
initial_points += 2 * min (k, assignable_points_from_list_ends)
return initial_points
if __name__=='__main__':
for _ in range(int(input().strip())):
print(solve()) | 8 | PYTHON3 |
from collections import *
from itertools import *
from bisect import *
def inp():
return int(input())
def arrinp():
return [int(x) for x in input().split()]
def main():
t = inp()
for _ in range(t):
n,k = arrinp()
s = [x for x in input()]
score = 0
for i in range(n):
if(i==0 and s[i]=="W"):
score +=1
elif(s[i]=='W' and s[i-1]=='W'):
score += 2
elif(s[i] == 'W' and s[i-1]!='W'):
score +=1
if(k==0):
print(score)
continue
if(score == 0):
print(1+(k-1)*2)
continue
#some W exists and K>0
diff = []
special = []
last = -1
i = 0
while(i<n):
if(s[i]=='W'):
if(last==-1):
last = i
if(i>0):
special.append(i)
else:
if(i-last-1>0):
diff.append(i-last-1)
last = i
i+=1
if(n-last-1>0):
special.append(n-last-1)
diff.sort()
for ele in diff:
if(ele<=k):
score += 2*ele + 1
k -= ele
elif(ele>k):
score += 2*k
k = 0
if(k==0):
break
if(k>0):
for ele in special:
if(ele<=k):
score += 2*ele
k -= ele
elif(ele>k):
score += 2*k
k = 0
if(k==0):
break
print(score)
if __name__ == '__main__':
main() | 8 | PYTHON3 |
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time : 2020/10/20 3:39 PM
# @Author : Songtao Li
import re
def cal_base_score(input_string):
W_list = re.findall("W+", input_string)
score = sum([2 * (len(w) - 1) + 1 for w in W_list])
return score
if __name__ == "__main__":
total_samples = int(input())
for i in range(total_samples):
length, modify = map(int, input().split())
string = input()
w_count = string.count("W")
l_count = length - w_count
base_score = cal_base_score(string)
if "W" not in string:
if modify == 0:
print(0)
else:
print(2 * modify - 1)
else:
s = re.search("(W.*W)", string)
if s is not None:
s = s.group()
else:
s = ""
stack = sorted(re.findall("L+", s), reverse=True)
first_l_seg = re.match("L+", string)
last_l_seg = re.match("L+", string[::-1])
while modify > 0 and len(stack) > 0:
seg = stack.pop()
modify -= 1
if seg == "L":
base_score += 3
else:
base_score += 2
stack.append(seg.replace("L", "", 1))
if first_l_seg is None:
len_first = 0
else:
len_first = len(first_l_seg.group())
if last_l_seg is None:
len_last = 0
else:
len_last = len(last_l_seg.group())
if modify > 0:
for _ in range(len_first+len_last):
base_score += 2
modify -= 1
if modify <= 0:
break
print(base_score)
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T = 1;
cin >> T;
while (T--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
vector<int> v;
int w = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') w++;
}
if (w == 0) {
cout << max(2 * k - 1, 0) << "\n";
continue;
}
w += k;
if (w >= n) {
cout << 2 * n - 1 << "\n";
continue;
}
int l = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'L')
l++;
else {
v.push_back(l);
l = 0;
}
}
if (l != 0) v.push_back(l);
if (s[0] == 'L') v.erase(v.begin());
if (s[n - 1] == 'L') v.erase(v.begin() + v.size() - 1);
sort(v.begin(), v.end());
int sp = 0;
int i;
for (i = 0; i < v.size(); i++) {
if (sp + v[i] > k) break;
sp += v[i];
}
int wl = v.size() - i;
cout << 2 * w - wl - 1 << "\n";
}
}
| 8 | CPP |
#This code is contributed by Siddharth
from bisect import *
import math
from collections import *
from heapq import *
from itertools import *
inf=10**18
mod=10**9+7
# ==========================================> Code Starts Here <=====================================================================
for _ in range(int(input())):
n,k=map(int,input().split())
s=list(input())
arr=[]
prev=-1
if n == 1:
if k:
print(1)
else:
if s[0] == 'W':
print(1)
else:
print(0)
continue
for i in range(n):
if s[i]=='W':
if prev==-1:
prev=i
elif i-prev==1:
prev=i
else:
arr.append(i-prev-1)
prev=i
if s.count('W')+k>=n or len(arr)==0:
print(max(0,min(n,s.count('W')+k)*2-1))
else:
arr.sort()
ans=s.count('W')
cnl=s.count('L')
par=len(arr)+1
for i in arr:
if i<=k:
k-=i
cnl-=i
par-=1
ans+=i
ans+=min(k,cnl)
print(max(0,ans*2-par))
| 8 | PYTHON3 |
t = int(input())
for _ in range(t):
n,k = map(int, input().split())
s = str(input())
base = 0
for i in range(n):
if s[i] == 'W':
if i != 0:
if s[i-1] == 'W':
base += 2
else:
base += 1
else:
base += 1
if base == 0:
x = n
if n == 1:
if k >= 1:
ans = 1
else:
ans = 0
elif n == 2:
if k >= 2:
ans = 3
elif k == 1:
ans = 1
else:
ans = 0
else:
if k >= x:
ans = 2*x-1
else:
if k == 0:
ans = 0
elif k == 1:
ans = 1
else:
ans = 1+(k-1)*2
print(ans+base)
continue
X= []
cur = s[0]
cnt = 0
for i in range(n):
if cur == s[i]:
cnt += 1
else:
if cur == 'L':
X.append([cnt, 0])
cnt = 1
cur = s[i]
else:
if cur == 'L':
X.append([cnt, 1])
if s[0] == 'L':
X[0][1] = 1
X.sort(key=lambda x:(x[1], x[0]))
#print(X)
ans = 0
for x, j in X:
if k >= x:
if j != 1:
ans += 2*x+1
else:
ans += 2*x
k -= x
else:
ans += k*2
break
print(ans+base)
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const long double epsylon = 1e-9;
const std::string PROGRAM_NAME = "ivo";
int main() {
int nt;
cin >> nt;
for (int it = 0; it < nt; ++it) {
int n, k;
cin >> n >> k;
string s;
getline(cin, s);
getline(cin, s);
vector<int> a;
int c = 0;
for (int i = 0; i < (int)s.size(); ++i) {
if (s[i] == 'W') {
if (c) {
if (c == i) {
c += 1000000;
}
a.push_back(c);
c = 0;
}
} else {
c++;
}
}
if (c) {
if (c == (int)s.size()) {
c += 1000000;
}
c += 1000000;
a.push_back(c);
}
sort(a.begin(), a.end());
int score = 0;
for (int i = 0; i < (int)s.size(); ++i) {
if (s[i] == 'W') {
if (i > 0 && s[i - 1] == 'W') {
score += 2;
} else {
score += 1;
}
}
}
for (int i = 0; i < (int)a.size() && k > 0; ++i) {
int sub = 0;
while (a[i] > 1000000) {
a[i] -= 1000000;
sub++;
}
if (k < a[i]) {
score += 2 * k;
score -= max(0, sub - 1);
k = 0;
} else {
score += 2 * a[i] + 1;
score -= sub;
k -= a[i];
}
}
cout << score << endl;
}
return 0;
}
| 8 | CPP |
tests = int (input())
for test in range (tests):
n, k = map (int, input().split())
s = 'L' + input().strip() + 'L'
res = 0
pr = 'L'
for c in s[1:-1]:
if c == 'W':
if pr == 'L':
res += 1
else:
res += 2
pr = c
r = 0
if res == 0:
r = 1
a = [len (c) for c in (s.split('W'))]
a = list(filter(lambda x: x != 0, a))
t = len(a)
for i in range (t):
if i == 0 or i == t - 1:
a[i] = 2 * a[i] - 2
else:
a[i] = 2 * a[i] + 1
b = sorted(a[1:-1])
for i in b:
if k * 2 + 1 < i:
res += k * 2
else:
res += i
k -= i // 2
if k <= 0:
break
if k > 0:
res += min (k * 2, a[0])
k -= a[0] // 2
if k > 0:
res += min (k * 2, a[t-1])
k -= a[t-1] // 2
# print (s)
# print (b, a[0], a[t-1])
# print (res)
if res > 0:
res -= r
res = min (res, n * 2 - 1)
print (res)
| 8 | PYTHON3 |
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
s = input().strip()
curr = n + 100
streaks = []
out = 0
wins = k
for i in range(n-1):
if s[i] == 'W' and s[i+1] == 'W':
out += 1
for c in s:
if c == 'W':
streaks.append(curr)
curr = 0
out += 1
wins += 1
else:
curr += 1
streaks.sort()
out += 2 * k
for v in streaks:
if v > 0 and v <= k:
k -= v
out += 1
print(min([2 * n - 1,out,max(0,2 * wins - 1)]))
| 8 | PYTHON3 |
import math
T=int(input())
for _ in range(T):
n,k=map(int,input().split())
s=list(input())
edge=0
ans=0
f=0
for i in s:
if i=='W':
f=1
break
if s[0]=='W':
ans=1
for i in range(1,n):
if s[i-1]=='W' and s[i]=='W':
ans+=2
elif s[i]=='W':
ans+=1
for i in range(n):
if s[i]=='W':
break
edge+=1
for j in range(n-1,-1,-1):
if s[j]=='W':
break
else:
edge+=1
st,en=i,j
l=[]
c=0
for i in range(st,en+1):
if s[i]=='L':
c+=1
else:
if c:
l.append(c)
c=0
l.sort()
for i in l:
if i<=k:
ans+=(2*i+1)
k-=i
else:
edge+=i
able=min(edge,k)
if f:
ans+=(2*able)
else:
ans+=(2*able-1)
print(max(ans,0))
| 8 | PYTHON3 |
def calculate(game):
if not game:
return 0
su = 1 if game[0] == 'W' else 0
prev = game[0]
for g in game[1:]:
if g == 'W':
su += 2 if prev == 'W' else 1
prev = 'W'
else:
prev = 'L'
return su
for t in range(int(input())):
n, k = map(int, input().split())
games = input()
gaps = list(map(len, games.split(('W'))))
front_end = []
bonus = 0
if len(gaps):
front_end.append(gaps.pop(0))
if len(gaps):
front_end.append(gaps.pop())
else:
bonus = -1 if k else 0
front_end = [f for f in front_end if f]
front_end.sort()
gaps = [g for g in gaps if g]
gaps.sort()
while k:
midgap = 0
if gaps:
top = gaps.pop(0)
midgap = 1
elif front_end:
top = front_end.pop(0)
else:
break
if top > k:
bonus += k*2
k = 0
else:
bonus += top*2 + midgap
k -= top
print(calculate(games) + bonus)
| 8 | PYTHON3 |
'''
|\_/|
| @ @ Woof!
| <> _
| _/\------____ ((| |))
| `--' |
____|_ ___| |___.'
/_/_____/____/_______|
I am here to gaurd this code, woof!
'''
from sys import stdin, stdout
from math import ceil, floor, sqrt, log, log2, log10
from collections import Counter
input = stdin.readline
def solve():
pass
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
s = input().strip()
curr = n + 100
streaks = []
out = 0
wins = k
for i in range(n-1):
if s[i] == 'W' and s[i+1] == 'W':
out += 1
for c in s:
if c == 'W':
streaks.append(curr)
curr = 0
out += 1
wins += 1
else:
curr += 1
streaks.sort()
out += 2 * k
for v in streaks:
if v > 0 and v <= k:
k -= v
out += 1
print(min([2 * n - 1,out,max(0,2 * wins - 1)])) | 8 | PYTHON3 |
for _ in range(int(input())):
n,k=map(int,input().split())
a=list(input())
f=False
loss=0
arr=[]
start=0
last=0
ans=0
if n==a.count("L") and k>0:
ans-=1
for i in range(n):
if a[i]=='W':
f=True
if f and i>0:
if a[i]=="L" and a[i-1]=="L":
loss+=1
elif a[i]=="L":
loss=1
elif loss!=0:
arr.append(loss)
loss=0
if loss!=0:
arr.append(loss)
if a[-1]!="W" and len(arr)>0:
last=arr.pop()
for i in range(n):
if a[i]=="L":
start+=1
else:
break
arr.sort()
if a[0]=="W":
ans+=1
for i in range(1,n):
if a[i]==a[i-1] and a[i]=="W":
ans+=2
elif a[i]=="W":
ans+=1
for i in arr:
if k-i>=0:
ans+=(i)*2
ans+=1
k-=i
else:
ans+=k*2
k=0
start,last=min(start,last),max(start,last)
if k-start>=0:
k-=start
ans+=(start*2)
else:
ans+=k*2
k=0
if k-last>=0:
k-=last
ans+=(last*2)
else:
ans+=k*2
k=0
print(ans)
| 8 | PYTHON3 |
if __name__ == '__main__':
t = int(input())
tag = []
for i in range(t):
n, k = map(int, input().split())
s = input()
cur, ans = k + 5, 0
tag.clear()
for j in range(n):
if s[j] == 'L':
cur += 1
else:
ans += 1 if cur > 0 else 2
if cur > 0:
tag.append(cur)
cur = 0
if cur == k + n + 5:
print(max(0, 2 * min(k, n) - 1))
continue
tag.sort()
for j in range(len(tag)):
if k >= tag[j]:
ans = ans + 2 * tag[j]
ans += 1
k -= tag[j]
ans += 2 * k
ans = min(ans, 2 * n - 1)
print(ans)
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const long long M = 1e5 + 5;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int beg = 0;
int end = 0;
int mv = 0;
while (mv < n && s[mv] == 'L') {
mv++;
beg++;
}
mv = n - 1;
while (mv >= 0 && s[mv] == 'L') {
mv--;
end++;
}
vector<pair<int, pair<int, int> > > len;
int i = beg;
while (i < n - end) {
if (s[i] == 'W') {
i++;
continue;
}
int shuru = i;
while (i < n - end && s[i] == 'L') i++;
int khatm = i - 1;
len.push_back(make_pair(khatm - shuru + 1, make_pair(shuru, khatm)));
}
sort(len.begin(), len.end());
if (beg >= end) {
len.push_back(make_pair(beg, make_pair(0, beg - 1)));
len.push_back(make_pair(end, make_pair(n - end, n - 1)));
} else {
len.push_back(make_pair(end, make_pair(n - end, n - 1)));
len.push_back(make_pair(beg, make_pair(0, beg - 1)));
}
for (i = 0; i < len.size(); i++) {
if (k >= len[i].first) {
k -= len[i].first;
if (len[i].second.first != 0) {
for (int j = len[i].second.first; j <= len[i].second.second; j++)
s[j] = 'W';
} else {
for (int j = len[i].second.second; j >= len[i].second.first; j--)
s[j] = 'W';
}
} else {
if (len[i].second.first != 0) {
for (int j = len[i].second.first; j <= len[i].second.second; j++) {
if (k == 0) break;
s[j] = 'W';
k--;
}
break;
} else {
for (int j = len[i].second.second; j >= len[i].second.first; j--) {
if (k == 0) break;
s[j] = 'W';
k--;
}
break;
}
}
}
int ans = 0;
i = 0;
while (i < n) {
if (s[i] == 'L') {
i++;
continue;
}
int ct = 0;
while (s[i] == 'W') {
ct++;
i++;
}
ans += 1 + (ct - 1) * 2;
}
cout << ans << '\n';
}
}
| 8 | CPP |
def solve():
x, y = map(int, input().split())
s = list(input())
v = []
ind = -1
ct = 0
st = 0
for n in range(len(s)):
if s[n] == 'L':
if st:
if ind == -1:
ind = n
ct += 1
else:
if ct:
v.append([ct, ind])
ct = 0
ind = -1
st = 1
v.sort(key=lambda x: x[0])
for n in v:
for k in range(n[1], n[1]+n[0]):
if y:
s[k] = 'W'
y -= 1
id = 0
for n in range(x):
if s[n] == 'L':
id += 1
if s[n] == 'W':
break
id -= 1
while id >= 0 and y:
s[id] = 'W'
id -= 1
y -= 1
id = x-1
while s[id] == 'L' and id > 0:
id -= 1
id += 1
while id < x and y:
s[id] = 'W'
id += 1
y -= 1
res = 0
st = 0
for n in s:
if n == 'W':
if st == 0:
res += 1
st = 1
else:
res += 2
else:
st = 0
print(res)
for _ in range(int(input())):
solve()
| 8 | PYTHON3 |
def calculate(game):
if not game:
return 0
su = 1 if game[0] == 'W' else 0
prev = game[0]
for g in game[1:]:
if g == 'W':
su += 2 if prev == 'W' else 1
prev = 'W'
else:
prev = 'L'
return su
for t in range(int(input())):
n, k = map(int, input().split())
games = input()
gaps = list(map(len, games.split(('W'))))
front_end = []
bonus = 0
if len(gaps):
front_end.append(gaps.pop(0))
if len(gaps):
front_end.append(gaps.pop())
else:
bonus = -1 if k else 0
front_end = [f for f in front_end if f]
front_end.sort()
gaps = [g for g in gaps if g]
gaps.sort()
while k:
if not gaps:
if not front_end:
break
top = front_end.pop(0)
if top > k:
bonus += k*2
k = 0
else:
bonus += top*2
k -= top
else:
top = gaps.pop(0)
if top > k:
bonus += k*2
k = 0
else:
bonus += top*2 + 1
k -= top
print(calculate(games) + bonus)
| 8 | PYTHON3 |
for i in range(int(input())):
n, k = map(int, input().split())
s = input()
wins = s.count('W') + k
if wins >= n:
print(2 * n - 1)
else:
streaks = int(s[0] == 'W') + s.count('LW') or int(wins > 0)
gaps = s.strip('L').replace('W', ' ').strip().split()
for g in sorted(map(len, gaps)):
if g > k:
break
k -= g
streaks -= 1
print(wins * 2 - streaks)
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
const int mod = 1e9 + 7;
const long long INF = 1e18;
vector<int> a;
char s[maxn];
void rua() {
int n, m, k = 0, ans = 0;
scanf("%d%d", &n, &m);
a.clear();
scanf("%s", s + 1);
for (int i = 1; i <= n; i++)
if (s[i] == 'L') k++;
m = min(m, k);
int ol = 0, ow = 0, ff = 0;
for (int i = 1; i <= n; i++) {
if (s[i] == 'L') {
ol++;
if (s[i - 1] == 'W') {
ans += 2 * ow - 1;
ow = 0;
}
} else {
ow++;
if (s[i - 1] == 'L') {
if (ff) a.push_back(ol);
ol = 0;
}
ff = 1;
}
}
if (ow) ans += 2 * ow - 1;
sort(a.begin(), a.end());
for (auto x : a) {
if (m < x) {
ans += 2 * m;
m = 0;
break;
}
ans += 2 * x + 1;
m -= x;
}
if (m) {
ans += 2 * m;
if (!ff) ans--;
}
printf("%d\n", ans);
}
int main() {
int t;
scanf("%d", &t);
while (t--) rua();
return 0;
}
| 8 | CPP |
def solve():
n, k = map(int, input().split())
s = input()
wn = 0
for c in s:
if c == 'W':
wn += 1
ln = 0
c = 0
while c < n and s[c] == 'L':
c += 1
ln += 1
a = c
c = len(s) - 1
ln = 0
while c >= 0 and s[c] == 'L':
c -= 1
ln += 1
b = c
ln = 0
d = [ 0 for _ in range(n) ]
for i in range(a, b + 1):
if s[i] == 'L':
ln += 1
else:
d[ln] += 1
ln = 0
ls = 0
K = k
for i in range(1, len(d)):
mn = min(k // i, d[i])
ls += d[i] - mn
k = k - mn * i
score = 2*min(n, wn + K) - (ls + 1)
score = max(0, score)
print(score)
def main():
t = int(input())
for _ in range(t):
solve()
main()
| 8 | PYTHON3 |
for _ in range(int(input())):
n,k = list(map(int,input().split()))
arr = list(input())
last = False
tot = 0
for i in range(n):
if arr[i] == "W":
if last:
tot+=2
else:
tot+=1
last = True
else:
last = False
globalFlag = tot > 0
dists = []
last = -1
flag = False
prefix = 0
sufix = 0
for i in range(n):
if not flag:
if arr[i] == "W":
prefix = i
last = i
flag = True
else:
if arr[i] == "W":
if i-last>1:
dists.append(i-last-1)
last = i
sufix = n-last-1
if not flag:
sufix = n
dists.sort()
# print(dists,prefix,sufix)
for i in range(len(dists)):
canAtThis = min(k,dists[i])
if k == 0:
break
if k >= dists[i]:
tot+=2*canAtThis+1
k-=canAtThis
else:
tot+=2*canAtThis
k-=canAtThis
if k == 0:
break
if k != 0 and sufix !=0 :
sufixGive = min(k,sufix)
# print(sufixGive)
tot+=1
tot+=sufixGive*2-1
k-=sufixGive
if not globalFlag:
tot-=1
if globalFlag:
if k!=0 and prefix!=0:
prefixGive = min(k,prefix)
tot+=prefixGive*2
print(tot)
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007, N = 500005;
long long a, b, c, d, e, f, g = 1, h[N], arr[N];
string s;
vector<pair<long long, long long>> v;
void solve() {
cin >> a >> b >> s;
v.clear();
long long l = 0, ok = 0, ans = 0;
;
for (long long i = 0; i < a; i++) {
if (s[i] == 'W') {
ans++;
if (i > 0 and s[i - 1] == 'W') ans++;
}
if (s[i] == 'L')
l++;
else if (ok == 0) {
if (l) v.push_back({2, l});
l = 0, ok = 1;
} else {
if (l) v.push_back({0, l});
l = 0;
}
}
if (ok == 0) {
cout << max(0ll, b * 2 - 1) << "\n";
return;
}
if (l) v.push_back({1, l});
sort(v.begin(), v.end());
for (long long i = 0; i < v.size(); i++) {
if (v[i].first == 0) {
if (b >= v[i].second) {
ans += 2 * v[i].second + 1;
b -= v[i].second;
} else {
ans += 2 * b;
break;
}
} else {
ans += 2 * min(b, v[i].second);
b -= min(b, v[i].second);
}
}
cout << ans << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> g;
while (g--) solve();
}
| 8 | CPP |
for _ in range(int(input())):
n, k = [int(i) for i in input().split()]
s = input()
chains = []
chain = 0
streak = False
if k + s.count("W") >= n:
print(2*n-1)
elif k == 0 and s.count("W")==0:
print(0)
else:
for char in s.strip("L").strip("W"):
if char == "W" and chain != 0:
chains.append(chain)
chain = 0
elif char == "L":
chain += 1
if chain != 0:
chains.append(chain)
chains.sort()
i = 0
total = 0
while chains and total+chains[i] <= k:
total += chains[i]
i += 1
if i >= len(chains):
break
print(2*(k+s.count("W"))-len(chains)-1+i) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int sz = 1e5 + 9, infP = INT_MAX, infN = INT_MIN, mod = 1e9 + 7,
eps = 1e-9;
void ini() { return; }
void solve() {
long long int n, m, k, l, r, ans = 0, cntL = 0;
string s;
cin >> n >> k >> s;
int ind[n];
m = -1;
for (int i = 0; i < n; i++) {
if (s[i] == 'L') {
ind[i] = m;
m = i;
} else {
ind[i] = m;
}
}
m = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'W' && m == 0) {
m = 1;
ans += 1;
continue;
}
if (s[i] == 'W' && m == 1) {
ans += 2;
continue;
}
if (s[i] == 'L') cntL++;
m = 0;
}
if (k == 0) {
cout << ans << "\n";
return;
}
if (cntL == n) {
if (k >= n) {
ans = n * 2;
ans -= 1;
} else {
ans = k * 2;
ans -= 1;
}
cout << ans << "\n";
return;
}
int start = 0, last = -1, stop = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') {
break;
}
last = i;
start++;
}
vector<int> lst;
for (int i = last + 1; i < n; i++) {
if (s[i] == 'W') {
if (i - 1 != last) {
lst.push_back(i - last - 1);
}
last = i;
}
}
for (int i = last + 1; i < n; i++) {
stop++;
}
sort(lst.begin(), lst.end());
;
for (int i = 0; i < lst.size(); i++) {
if (lst[i] <= k) {
ans += lst[i] * 2;
ans++;
k -= lst[i];
} else {
ans += k * 2;
k = 0;
break;
}
}
if (k == 0) {
cout << ans << "\n";
return;
}
if (stop >= k) {
ans += k * 2;
k = 0;
} else {
ans += stop * 2;
k = k - stop;
}
if (k == 0) {
cout << ans << "\n";
return;
}
if (start >= k) {
ans += k * 2;
k = 0;
} else {
ans += start * 2;
k = k - stop;
}
cout << ans << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
int t = 1;
cin >> t;
while (t--) solve();
}
| 8 | CPP |
for _ in " "*int(input()):
n,k=map(int,input().split())
s=list(input())
if "W" not in s:
print(max((min(k,n)*2)-1,0))
elif k >= s.count("L"):
print((n*2)-1)
else:
cnt=[]
sm=0
for i in range(n):
if s[i] == "W":
sm+=1
ind=s.index("W")
for i in range(ind+1,n):
if s[i] == "W":
cnt.append(i-ind-1)
ind=i
cnt.sort()
for i in cnt:
if k >= i:
sm+=(2*i)+1
k-=i
if k>0:
sm+=(2*k)
print(sm) | 8 | PYTHON3 |
import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
#from copy import *
#from bisect import *
from heapq import *
#from heapq import *
#from math import gcd,ceil,sqrt
#from itertools import permutations as prm,product
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
#sys.setrecursionlimit(10**6)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
di=[[-1,0],[1,0],[0,1],[0,-1]]
def string(s):
return "".join(s)
def fori(n):
return [fi() for i in range(n)]
def inc(d,c,x=1):
d[c]=d[c]+x if c in d else x
def bo(i):
return ord(i)-ord('A')
def li():
return [int(xx) for xx in input().split()]
def fli():
return [float(x) for x in input().split()]
def comp(a,b):
if(a>b):
return 2
return 2 if a==b else 0
def gi():
return [xx for xx in input().split()]
def cil(n,m):
return n//m+int(n%m>0)
def fi():
return int(input())
def pro(a):
return reduce(lambda a,b:a*b,a)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
def gh():
sys.stdout.flush()
def isvalid(i,j):
return 0<=i<n and 0<=j<m and a[i][j]!="."
def bo(i):
return ord(i)-ord('a')
def graph(n,m):
for i in range(m):
x,y=mi()
a[x].append(y)
a[y].append(x)
t=fi()
while t>0:
t-=1
n,k=mi()
s=si()
a=[0]*(n)
ans=0
for i in range(n):
if s[i]=='W':
a[i]+=1
if i>0 and a[i-1]:
ans+=2
else:
ans+=1
l=[]
d=[]
prev=-1
for i in range(n):
if a[i]:
if prev==-1 and i:
d.append([1,i])
elif i and i-prev-1:
d.append([0,i-prev-1])
prev=i
if prev!=n-1 :
d.append([1,n-prev-1])
if a.count(1)==0:
print(1+2*(k-1) if k>0 else 0)
continue
d.sort()
for i in range(len(d)):
if k-d[i][1]>=0:
ans+=(d[i][1])*2
if d[i][0]==0:
ans+=1
k-=d[i][1]
elif k:
ans+=k*2
k=0
#print(*a)
print(ans)
#print(d)
| 8 | PYTHON3 |
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)
| 8 | PYTHON3 |
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)
| 8 | PYTHON3 |
for t in range(int(input())):
n, k = map(int, input().split())
a = input()
b = [0] * n
s = 0
c = 0
w = a.count('W')
if k >= (n - w):
print(2 * n - 1)
elif w == 0:
print(max(0, 2 * k - 1))
else:
f = a.find('W')
for i in range(f, n):
if a[i] == 'W':
s += 1
if i > 0 and a[i - 1] == 'W':
s += 1
b[c] += 1
c = 0
else:
c += 1
for j in range(1, n):
if k >= j * b[j]:
s += b[j] * (2 * j + 1)
k -= j * b[j]
else:
m = k // j
r = k % j
s += m * (2 * j + 1) + 2 * r
k = 0
break
s += 2 * k
print(s)
| 8 | PYTHON3 |
def solve(record, length, changes):
if record == 'L' * length:
return changes * 2 - 1 if changes > 0 else 0
state = 'N'
loss_runs = []
win_runs = []
counter = 0
bonus = 0
score = 0
for i in record:
if state == 'N':
if i == 'L':
bonus += 1
else:
state = 'W'
counter += 1
else:
if state == 'W':
if i == 'W':
counter += 1
else:
win_runs.append(counter)
counter = 1
state = 'L'
else:
if i == 'L':
counter += 1
else:
loss_runs.append(counter)
counter = 1
state = 'W'
if state == 'W':
win_runs.append(counter)
else:
bonus += counter
for i in win_runs:
score += 2*i-1
loss_runs = sorted(loss_runs)
for i in loss_runs:
if changes >= i:
score += 2*i+1
changes -= i
else:
score += 2*changes
changes = 0
if changes != 0:
score += min(bonus*2, changes*2)
return score
t = int(input())
for _ in range(t):
l, c = [int(i) for i in input().split()]
arr = input()
print(solve(arr, l, c))
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
long long int power(long long int b, long long int e) {
if (e == 0) return 1;
if (e & 1) return b * power(b * b, e / 2);
return power(b * b, e / 2);
}
long long int gcd(long long int a, long long int b) {
if (a == 0) return b;
if (b == 0) return a;
if (a == b) return a;
if (a > b) return gcd(a - b, b);
return gcd(a, b - a);
}
bool compare(const pair<long long int, long long int>& i,
const pair<long long int, long long int>& j) {
return i.first < j.first;
}
void solve() {
long long int n, sum = 0, k, ans = 0, l1 = 0, a = 0, flag = 0, f = 1;
cin >> n >> k;
string s;
cin >> s;
vector<long long int> v;
for (long long int i = 0; i < n; i++) {
if (f == 1) {
if (s[i] == 'L')
l1++;
else {
f = 2;
flag = 1;
}
} else if (flag == 0) {
if (s[i] == 'W') {
flag = 1;
v.push_back(a);
a = 0;
} else
a++;
} else {
f++;
if (s[i] == 'L') {
a++;
flag = 0;
}
}
}
if (s[0] == 'W') ans++;
for (long long int i = 1; i < n; i++) {
if (s[i] == 'W' && s[i - 1] == 'L')
ans++;
else if (s[i] == 'W' && s[i - 1] == 'W') {
ans += 2;
}
}
for (long long int i = 0; i < v.size(); i++) {
}
sort(v.begin(), v.end());
for (long long int i = 0; i < v.size(); i++) {
if (k >= v[i]) {
ans += 2 * v[i] + 1;
k -= v[i];
} else {
ans += 2 * k;
cout << ans << "\n";
return;
}
}
if (ans == 0) {
if (l1 < k)
cout << 2 * l1 - 1 << "\n";
else {
if (k)
cout << 2 * k - 1 << "\n";
else
cout << 0 << "\n";
}
return;
}
if (l1 + a < k) {
ans += 2 * (l1 + a);
} else
ans += 2 * k;
cout << ans << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
long long int t = 1;
cin >> t;
for (long long int i = 0; i < t; i++) {
solve();
}
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int cur = 0;
vector<int> v;
int c = s[0] == 'L';
int ans = s[0] == 'W';
for (int i = 1; i < s.size(); i++) {
if (s[i] == 'W') {
ans += 1 + (s[i - 1] == 'W');
} else
c++;
}
if (c == n) {
cout << max(0, k * 2 - 1) << endl;
return;
}
for (auto i : s) {
if (i == 'L')
cur++;
else {
v.push_back(cur);
cur = 0;
}
}
if (v.size()) {
cur += v[0];
swap(v[0], v[v.size() - 1]);
v.pop_back();
}
sort((v).begin(), (v).end());
int ind = 0;
int d = 0;
while (ind < v.size() && d < k) {
if (v[ind] == 0) {
ind++;
continue;
} else {
if (v[ind] == 1)
ans += 3;
else
ans += 2;
v[ind]--;
d++;
}
}
ans += (min(k - d, cur) * 2);
cout << ans << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
cin >> t;
while (t--) {
solve();
}
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
using LL = long long int;
using uLL = unsigned long long int;
using uint = unsigned int;
using ld = long double;
inline bool compare(pair<int, int> a, pair<int, int> b) {
if (a.first == b.first) {
return a.second < b.second;
}
return a.first > b.first;
}
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int res = (s[0] == 'W');
for (int i = 1; i < n; i++) {
if (s[i] == 'W') {
if (s[i - 1] == 'W') {
res += 2;
} else {
res += 1;
}
}
}
vector<int> next_w(n);
int pos = 100000000;
for (int i = n - 1; i >= 0; i--) {
next_w[i] = pos;
if (s[i] == 'W') pos = i;
}
if (pos == 100000000) {
cout << max(k * 2 - 1, 0) << '\n';
continue;
}
vector<pair<int, int> > wektor;
for (int i = 0; i < n; i++) {
if (s[i] == 'W' && next_w[i] != i + 1 && i != n - 1) {
wektor.push_back({next_w[i] - 1 - i, i});
}
}
sort(wektor.begin(), wektor.end());
for (auto x : wektor) {
int j = x.second + 1;
while (k > 0 && j < n && s[j] == 'L') {
k--;
res += 2;
j++;
}
if (j < n && s[j] == 'W') {
res++;
}
if (k == 0) break;
}
if (pos != 100000000) {
int i = pos - 1;
while (k > 0 && i >= 0) {
k--;
res += 2;
i--;
}
}
cout << res << '\n';
}
return 0;
}
| 8 | CPP |
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)
| 8 | PYTHON3 |
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) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const long long int inf = 1e18;
const long long int mod = 1e9 + 7;
const long long int MOD = 998244353;
template <class c>
struct rge {
c b, e;
};
template <class c>
rge<c> range(c i, c j) {
return rge<c>{i, j};
}
template <class c>
auto dud(c *x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct debug {
template <class c>
debug &operator<<(const c &) {
return *this;
}
};
vector<char *> tokenizer(const char *args) {
char *token = new char[111];
strcpy(token, args);
token = strtok(token, ", ");
vector<char *> v({token});
while ((token = strtok(NULL, ", "))) v.push_back(token);
return reverse(v.begin(), v.end()), v;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
void debugg(vector<char *> args) { cerr << "\b\b "; }
#pragma clang diagnostic pop
template <typename Head, typename... Tail>
void debugg(vector<char *> args, Head H, Tail... T) {
debug() << " [" << args.back() << ": " << H << "] ";
args.pop_back();
debugg(args, T...);
}
template <typename T>
T power(T a, T b) {
if (b == 0) return 1;
if (b == 1)
return a;
else {
T res = (power(a, b / 2));
if (b % 2) {
return (res * res * a);
} else {
return res * res;
}
}
}
template <typename T>
T power(T a, T b, T modulo) {
if (b == 0) return 1;
if (b == 1)
return a;
else {
T res = (power(a, b / 2, modulo) % modulo);
if (b % 2) {
return ((((res % modulo) * (res % modulo)) % modulo) * (a % modulo)) %
modulo;
} else {
return ((res % modulo) * (res % modulo)) % modulo;
}
}
}
template <typename T>
T gcd(T a, T b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
void factorial(vector<long long int> &fact, long long n) {
fact.resize(n + 1, 1);
fact[0] = 1;
fact[1] = 1;
for (int i = 2; i <= n; ++i) {
fact[i] = ((fact[i - 1] % mod) * (i % mod)) % mod;
}
}
long long mod_inv(long long a) {
return (power<long long>(a, mod - 2, mod)) % mod;
}
long long ncr(long long n, long long r, vector<long long int> &fact) {
if (r > n or n < 0 or r < 0) return 0LL;
return (((fact[n] % mod) * (mod_inv(fact[n - r]) % mod)) % mod *
(mod_inv(fact[r]) % mod)) %
mod;
}
template <typename T>
bool asc(pair<T, T> &a, pair<T, T> &b) {
if (a.first == b.first) {
return a.second < b.second;
}
return a.first > b.first;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
cin >> t;
while (t--) {
long long n, k;
cin >> n >> k;
string s;
cin >> s;
long long sum = 0;
vector<pair<long long, pair<long long, long long>>> v;
long long z = -2;
long long p = -1;
for (int i = 0; i < ((long long)(s).size());) {
long long j = i;
if (z == -2 and s[i] == 'W') z = i;
if (s[i] == 'W') p = i;
if (s[i] == 'L') {
while (i < ((long long)(s).size()) and s[i] == 'L') {
i++;
}
if (j != 0 and i != n)
v.emplace_back(
make_pair(i - j, pair<long long, long long>{j, i - 1}));
} else {
i++;
}
}
{};
sort((v).begin(), (v).end());
{};
for (int i = 0; i < ((long long)(v).size()) and k > 0; ++i) {
long long x = v[i].first;
long long a = v[i].second.first;
long long b = v[i].second.second;
long long j = b;
{};
while (b + 1 < n and j >= a and k > 0 and s[j] == 'L') {
s[j] = 'W';
j--;
k--;
}
j = a;
while (a - 1 >= 0 and j <= b and k > 0 and s[j] == 'L') {
s[j] = 'W';
j++;
k--;
}
}
{};
{};
p++;
while (k > 0 and p < n and p >= 0 and s[p] == 'L') {
s[p] = 'W';
k--;
p++;
}
z--;
while (k > 0 and z >= 0 and z < n and s[z] == 'L') {
s[z] = 'W';
k--;
z--;
}
sum = 0;
{};
for (int i = 0; i < ((long long)(s).size()); ++i) {
if (s[i] == 'L') {
continue;
}
if (i - 1 >= 0 and s[i] == 'W' and s[i - 1] == 'W') {
sum += 2;
} else {
sum += 1;
}
}
cout << ((sum)) << "\n";
;
}
return 0;
}
| 8 | CPP |
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()
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int T, N, K;
string stat;
vector<int> v;
void process() {
int l = 0, r = 0, ans = 0, W_count = 0;
bool L_Flag = false, W_Flag = false;
v.clear();
for (int i = 0; i < N; i++) {
if (stat[i] == 'W') {
if (W_Flag)
ans += 2;
else {
ans += 1;
W_Flag = true;
}
} else {
W_Flag = false;
}
}
if (stat[0] == 'W') W_count++;
for (int i = 1; i < N; i++) {
if (stat[i] == 'W') W_count++;
if (stat[i - 1] == 'W' && stat[i] == 'L') {
l = i;
L_Flag = true;
} else if (L_Flag) {
if (stat[i] == 'W') {
v.emplace_back(i - l);
L_Flag = false;
}
}
}
int L_count = N - W_count;
if (K >= L_count) {
cout << 2 * N - 1 << "\n";
return;
}
if (W_count == 0) {
cout << std::max(2 * K - 1, 0) << "\n";
return;
}
sort(v.begin(), v.end());
const int v_size = v.size();
int ptr = 0;
while (ptr < v_size && v[ptr] <= K) {
ans += 2 * v[ptr] + 1;
K -= v[ptr];
ptr++;
}
if (K > 0) ans += 2 * K;
cout << ans << "\n";
}
void cf_input() {
cin >> T;
for (int t = 0; t < T; t++) {
cin >> N >> K;
cin >> stat;
process();
}
}
int main() {
std::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cf_input();
return 0;
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
vector<int> blocks;
for (int i = 0; i < n; ++i) {
bool good_start = (i > 0);
if (s[i] == 'W') {
continue;
}
int len = 0;
while (i < n && s[i] == 'L') {
len++;
i++;
}
if (good_start && i != n) {
blocks.push_back(len);
}
}
sort(blocks.begin(), blocks.end());
int answer = 0;
int remaining = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == 'W') {
answer++;
} else {
remaining++;
}
if (s[i] == 'W' && i > 0 && s[i - 1] == 'W') answer++;
}
if (remaining == n && k > 0) {
answer--;
}
for (int x : blocks) {
if (k >= x) {
k -= x;
answer += 2 * x + 1;
remaining -= x;
} else {
break;
}
}
answer += 2 * min(k, remaining);
cout << answer << endl;
}
int main(int argc, char const *argv[]) {
int T;
cin >> T;
for (int t = 0; t < T; t++) solve();
return 0;
}
| 8 | CPP |
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
for j in range(int(input())):
n,k=map(int,input().split())
vals=[k for k in input()]
init=0
for s in range(n):
if vals[s]=="W":
if s>0 and vals[s-1]=="W":
init+=2
else:
init+=1
ans=[];chain=[];storef=[];storel=[]
for s in range(n):
if vals[s]=="L":
chain.append(s)
else:
if len(chain)>0:
if chain[0]==0:
storef=chain.copy()
elif chain[-1]==n-1:
storel=chain.copy()
else:
ans.append((len(chain),chain.copy()))
chain.clear()
if len(chain)>0:
if chain[0]==0:
storef=chain.copy()
elif chain[-1]==n-1:
storel=chain.copy()
else:
ans.append((len(chain),chain.copy()))
ans.sort(key=lambda x: x[0],reverse=True)
while k>0 and len(ans)>0:
v0=ans.pop()[1]
if k>=len(v0):
k-=len(v0);init+=2*len(v0)+1
else:
init+=2*k;k=0
if len(storel)>0 and k>0:
if k>=len(storel):
k-=len(storel);init+=2*len(storel)
else:
init+=2*k;k=0
if len(storef)>0 and k>0:
if k>=len(storef):
if storef[-1]==n-1:
k-=len(storef);init+=1+2*(len(storef)-1)
else:
k-=len(storef);init+=2*len(storef)
else:
if storef[-1]==n-1:
init+=1+2*(k-1);k=0
else:
init+=2*(k);k=0
print(init) | 8 | PYTHON3 |
import sys
import bisect as bi
import collections as cc
I=lambda:list(map(int,input().split()))
for tc in range(int(input())):
n,k=I()
s=list(input())
if s.count('W')==0:
now=min(k,n)
print(max(0,1+(2*(now-1))))
continue
i=0
gap=[]
for i in range(n):
if s[i]=='W':
gap.append(i)
ne=[]
for i in range(len(gap)-1):
ne.append([gap[i],gap[i+1],gap[i+1]-gap[i]-1])
ne.sort(key=lambda x:x[2])
for i in ne:
now=i[0]+1
while now<i[1] and k:
#print("agg",now,k,i)
s[now]='W'
now+=1
k-=1
if not k:
break
temp=[]
if s[0]!='W':
temp.append([-1,gap[0],gap[0]-(-1)-1])
if s[-1]!='W':
temp.append([gap[-1],n,n-gap[-1]-1])
temp.sort(key=lambda x:x[2])
for i in temp:
if i[0]==-1:
now=i[1]-1
while now>=0 and k:
k-=1
s[now]='W'
now-=1
else:
now=i[0]+1
while now<i[1] and k:
s[now]='W'
k-=1
now+=1
if not k:
break
f=0
cnt=0
ans=0
#print(gap)
#print(ne)
#print(s)
for i in range(n):
if not f and s[i]=='W':
f=1
ans+=1
elif f and s[i]=='W':
ans+=2
else:
f=0
print(ans) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
template <class T>
bool ckmin(T& a, const T& b) {
return a > b ? a = b, true : false;
}
template <class T>
bool ckmax(T& a, const T& b) {
return a < b ? a = b, true : false;
}
template <typename T>
true_type const_iterator_check(typename T::const_iterator*);
template <typename T>
false_type const_iterator_check(...);
template <typename T>
struct IsC : decltype(const_iterator_check<T>(nullptr)) {};
template <>
struct IsC<string> : false_type {};
template <typename C>
typename enable_if<IsC<C>::value, ostream&>::type operator<<(ostream&,
const C&);
template <typename T1, typename T2>
ostream& operator<<(ostream&, const pair<T1, T2>&);
template <typename... T>
using TS = tuple_size<tuple<T...>>;
template <size_t idx, typename... T>
typename enable_if<TS<T...>::value == idx + 1, ostream&>::type operator<<(
ostream& o, const tuple<T...>& t) {
return o << ", " << get<idx>(t) << ')';
}
template <size_t idx, typename... T>
typename enable_if<0 < idx && idx + 1 < TS<T...>::value, ostream&>::type
operator<<(ostream& o, const tuple<T...>& t) {
return operator<<<idx + 1>(o << ", " << get<idx>(t), t);
}
template <size_t idx = 0, typename... T>
typename enable_if<1 < TS<T...>::value && !idx, ostream&>::type operator<<(
ostream& o, const tuple<T...>& t) {
return operator<<<idx + 1>(o << '(' << get<idx>(t), t);
}
template <typename T>
ostream& operator<<(ostream& o, const tuple<T>& t) {
return o << get<0>(t);
}
template <typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2>& p) {
return o << make_tuple(p.first, p.second);
}
template <typename C>
typename enable_if<IsC<C>::value, ostream&>::type operator<<(ostream& o,
const C& c) {
o << '[';
for (auto it = c.cbegin(); it != c.cend(); ++it)
o << *it << (next(it) != c.cend() ? ", " : "");
return o << ']';
}
template <typename T>
void tprint(vector<vector<T>>& v, size_t width = 0, ostream& o = cerr) {
if (!0) return;
for (const auto& vv : v) {
for (const auto& i : vv) o << setw(width) << i;
o << '\n';
}
}
void solve() {
int n, k;
string s;
cin >> n >> k >> s;
int lCnt = 0;
for (char c : s)
if (c == 'L') lCnt++;
if (lCnt == n) {
cout << max(0, 2 * (k - 1) + 1) << '\n';
return;
}
int start = 0;
while (s[start] == 'L') start++;
int end = n - 1;
while (s[end] == 'L') end--;
vector<pair<int, int>> cnts;
for (int i = start; i <= end;) {
while (s[i] == 'W') i++;
int cnt = 0;
while (i + cnt <= end && s[i + cnt] == 'L') cnt++;
if (cnt) cnts.emplace_back(cnt, i);
i += cnt;
}
sort((cnts).begin(), (cnts).end());
for (auto [amt, ind] : cnts) {
for (auto i = (ind); (i) < (ind + min(amt, k)); ++(i)) s[i] = 'W';
k -= min(amt, k);
}
int k2 = k;
for (auto i = (end + 1); (i) < (min(n, end + 1 + k2)); ++(i)) {
k--;
s[i] = 'W';
}
for (auto i = (0); (i) < ((min(k, start))); ++(i)) s[start - 1 - i] = 'W';
long long score = 0;
for (int i = 0; i < n;) {
if (s[i] == 'L') {
i++;
} else {
score++;
i++;
while (i < n && s[i] == 'W') {
score += 2;
i++;
}
}
}
cout << score << '\n';
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
int tc = 1;
cin >> tc;
for (auto i = (1); (i) < (tc + 1); ++(i)) {
solve();
}
}
| 8 | CPP |
for _ in range(int(input())):
n,k=map(int,input().split())
s=input()
L=s.count('L')
W=s.count('W')
if L<=k:
print(2*(n-1)+1)
continue
if L==n and k!=0:
print((k-1)*2+1)
continue
count=0
p=0
if s[0]=='W':
count+=1
p=1
for i in range(1,n):
if s[i]=='W' and p:
count+=2
elif s[i]=='W':
count+=1
p=1
else:
p=0
continue
if k==0:
print(count)
continue
temp=s[::-1]
t=s
for i in range(n):
if temp[i]=='L':
continue
else:
break
temp=temp[i:]
temp=temp[::-1]
#print(temp)
s=temp
m=i
#print(m,s,t)
l=[]
p=0
c=0
for i in range(1,len(s)):
if s[i-1]=='W' and s[i]=='L':
c+=1
p=1
elif s[i-1]=='L' and s[i]=='L' and p:
c+=1
elif s[i-1]=='L' and s[i]=='W':
p=0
if c!=0:
l.append(c)
c=0
else:
continue
if c!=0:
l.append(c)
l.sort()
#print(count)
#print(count,t)
for i in l:
if k<=0:
break
if k>=i:
k-=i
count+=(2*i+1)
else:
break
if len(l) and k<=max(l):
count+=(k*2)
print(count)
else:
if m>k:
count=count+(k*2)
k=0
print(count)
else:
count+=(m*2)
k-=m
for i in range(n):
if t[i]=='W':
break
if i>k:
print(count+(k)*2)
else:
print(count+(k-i)*2)
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
template <class A, class B>
ostream &operator<<(ostream &out, const pair<A, B> &a) {
return out << "(" << a.first << "," << a.second << ")";
}
template <class A>
ostream &operator<<(ostream &out, const vector<A> &a) {
for (const A &it : a) out << it << " ";
return out;
}
template <class A, class B>
istream &operator>>(istream &in, pair<A, B> &a) {
return in >> a.first >> a.second;
}
template <class A>
istream &operator>>(istream &in, vector<A> &a) {
for (A &i : a) in >> i;
return in;
}
ifstream cinn("in.txt");
ofstream coutt("out.txt");
long long poww(const long long &a, long long b,
const long long &m = 1000000007) {
if (b == 0) return 1;
long long first = poww(a, b / 2, m);
first = first * first % m;
if (b & 1) first = first * a % m;
return first;
}
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
long long _sum(long long n) { return (n * (n + 1)) / 2; }
bool isPalindrome(string str) {
long long l = 0;
long long h = str.length() - 1;
while (h > l) {
if (str[l++] != str[h--]) {
return false;
}
}
return true;
}
long long fact(long long n) {
if (n == 0) return 1;
return n * fact(n - 1);
}
long long distSq(pair<long long, long long> p, pair<long long, long long> q) {
return (p.first - q.first) * (p.first - q.first) +
(p.second - q.second) * (p.second - q.second);
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long t, n, c, h, b, m, k, f, f2, t2, t3, i, j, ans, mnt, mxt, r, j1, j2;
cin >> t;
while (t--) {
cin >> n >> k;
string s;
cin >> s;
long long w = 0, ws = 0, l = 0;
vector<long long> loss;
for (i = 0; i < (long long)s.length(); i++) {
if (s[i] == 'W') {
w++;
if (i == 0 || s[i - 1] == 'L') ws++;
}
if (s[i] == 'L') {
l++;
if (i == 0 || s[i - 1] == 'W') loss.push_back(0);
loss.back()++;
}
}
if (k >= l) {
cout << 2 * n - 1 << '\n';
continue;
}
if (w == 0) {
if (k == 0)
cout << 0 << '\n';
else
cout << 2 * k - 1 << '\n';
continue;
}
w += k;
if (s[0] == 'L') loss[0] = 1e15;
if (s[n - 1] == 'L') loss.back() = 1e15;
sort((loss).begin(), (loss).end());
for (i = 0; i < loss.size(); i++) {
if (k < loss[i]) break;
k -= loss[i];
ws--;
}
cout << 2 * w - ws << '\n';
}
}
| 8 | CPP |
# n, k = list(map(int, input().split()))
# s = list(input())
# k = 7
# n = len(s)
for _ in range(int(input())):
n, k = list(map(int, input().split()))
s = list(input())
o = -1
def score(s):
if (s[0] == 'W'):
ans = 1
x = 1
else:
ans = 0
x = 0
for i in range(1, len(s)):
if (s[i] == 'W' and x == 1):
ans += 2
elif (s[i] == 'W' and x == 0):
x = 1
ans += 1
else:
x = 0
return ans
for i in range(n):
if (s[i] == 'W'):
o = i
break
o1 = -2
for i in range(n - 1, -1, -1):
if (s[i] == 'W'):
o1 = i
break
if (k == 0):
print(score(s))
elif (o == -1 or o1 == o):
print(2 * min(k + (o1 == o), n) - 1)
else:
r = []
st = o + 1
for j in range(o + 1, o1 + 1):
if (s[j] == 'W'):
r.append([st, j])
st = j + 1
r = sorted(r, key=lambda x: x[1] - x[0])
for j in r:
for d in range(j[0], j[1]):
if (k > 0):
k -= 1
s[d] = 'W'
else:
break
# print('ada',k)
for d in range(o - 1, -1, -1):
if (k > 0):
k -= 1
s[d] = 'W'
else:
break
for d in range(o1 + 1, len(s)):
if (k > 0):
k -= 1
s[d] = 'W'
else:
break
# print(s)
print(score(s))
# print(s.count('W'))
| 8 | PYTHON3 |
def main():
t = int(input())
for _ in range(t):
(n, k) = (int(x) for x in input().split())
s = input()
print(solver(s, n, k))
def solver(s, n, k):
cur_score = getCurScore(s)
#print(cur_score)
lcount = s.count('L')
if lcount <= k:
return 2 * n - 1
elif lcount == n:
return max(2 * k - 1, 0)
llist = []
i = s.find('W')
cur = 0
for c in s[i:]:
if c == 'L':
cur += 1
else:
if cur != 0:
llist.append(cur)
cur = 0
#print(llist)
llist.sort()
point_increase = 0
for x in llist:
if x <= k:
point_increase += (2 * x + 1)
k -= x
else:
point_increase += (2 * k)
return cur_score + point_increase
point_increase += (2 * k)
return cur_score + point_increase
# while i != len(s):
# while s[i] == 'W':
# firstL = i
# while s[i] == 'L':
# for c in s:
# if c == 'W':
# if cur != 0:
# consecutives.append(cur)
# cur = 0
# else:
# cur += 1
# last = cur
#print(consecutives)
def getCurScore(s):
score = 0
if s[0] == 'W':
score += 1
for i in range(1, len(s)):
if s[i] == 'W':
if s[i - 1] == 'W':
score += 2
else:
score += 1
return score
#print(solver('WLWLL', 5, 2))
#print(solver('LLLWWL', 6, 5))
#print(solver('LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL', 40, 7))
main()
#x = 'WWWLWWLL'
#print(x.find('L')) | 8 | PYTHON3 |
# region smaller_fastio
from sys import stdin, stdout
from os import path
if (path.exists('input.txt')):
# ------------------Sublime--------------------------------------#
stdin = open('input.txt', 'r');
stdout = open('output.txt', 'w');
def I():
return (int(input()))
def In():
return (map(int, input().split()))
else:
# ------------------PYPY FAst I/o--------------------------------#
def I():
return (int(stdin.readline()))
def In():
return (map(int, stdin.readline().split()))
def S():
return (stdin.readline().rstrip())
def Sn():
return (stdin.readline().split(' '))
# endregion
def f(n, k, s):
wins = loss = 0
win_streak = 0
lose_streaks = []
for i in range(n):
if s[i] == 'W':
wins += 1
if i == 0 or s[i - 1] == 'L':
win_streak += 1
else:
loss += 1
if i == 0 or s[i - 1] == 'W':
lose_streaks.append(0)
lose_streaks[-1] += 1
if k >= loss:
return 2 * n - 1
if wins == 0:
if k == 0:
return 0
return 2 * k - 1
if s[0] == 'L':
lose_streaks[0] = 1e9
if s[-1] == 'L':
lose_streaks[-1] = 1e9
wins += k
lose_streaks.sort()
for i in lose_streaks:
if i > k:
break
k -= i
win_streak -= 1
return 2 * wins - win_streak
def func():
st = ''
t = I()
for _ in range(t):
n, k = In()
s = input()
st = '\n'.join((st, str(f(n, k, s))))
print(st.lstrip())
if __name__ == '__main__':
func()
| 8 | PYTHON3 |
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)
| 8 | PYTHON3 |
from sys import stdin
t = int(stdin.readline())
for i in range(t):
n, k = tuple(int(x) for x in stdin.readline().split())
line = 'L' * (k+1) + stdin.readline()[:-1] + 'L' * (k+1)
score = 0
flag = False
for char in line:
if char == 'W':
if flag:
score += 2
else:
score += 1
flag = True
else:
flag = False
seq = sorted(len(x) for x in line.split('W'))
if len(seq) == 1:
if k == 0:
print(0)
else:
print(2*k-1)
continue
for item in seq:
if item == 0:
continue
if k - item >= 0:
k -= item
score += 2 * (item-1) + 3
elif k > 0:
score += 2 * k
break
else:
break
print(min(score, 2*n-1))
| 8 | PYTHON3 |
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("unroll-loops")
using namespace std;
template <typename A>
ostream &operator<<(ostream &cout, vector<A> const &v);
template <typename A, typename B>
ostream &operator<<(ostream &cout, pair<A, B> const &p) {
return cout << "(" << p.first << ", " << p.second << ")";
}
template <typename A>
ostream &operator<<(ostream &cout, vector<A> const &v) {
cout << "[";
for (int i = 0; i < v.size(); i++) {
if (i) cout << ", ";
cout << v[i];
}
return cout << "]";
}
template <typename A, typename B>
istream &operator>>(istream &cin, pair<A, B> &p) {
cin >> p.first;
return cin >> p.second;
}
const long long MAXN = 1e5 + 7;
void check() {
long long n, k;
cin >> n >> k;
k = min(n, k);
string s;
cin >> s;
vector<long long> a, b;
long long cur = 0, len = 0;
for (int i = 0; i < n; i++) {
long long x = (s[i] == 'W');
if (x != cur) {
if (cur == 0)
a.push_back(len);
else
b.push_back(len);
cur = x;
len = 0;
}
len++;
}
if (cur == 0)
a.push_back(len);
else {
b.push_back(len);
a.push_back(0);
}
long long cz = 0;
for (long long &x : a) cz += x;
if (cz <= k) {
cout << 2 * n - 1 << "\n";
return;
}
if (b.empty()) {
cout << max(0LL, 2 * k - 1) << "\n";
return;
}
long long ans = 0;
for (long long &x : b) ans += 2 * x - 1;
a.pop_back();
reverse(a.begin(), a.end());
a.pop_back();
sort(a.begin(), a.end());
ans += 2 * k;
for (long long &x : a) {
if (x <= k)
ans++, k -= x;
else
break;
}
cout << ans << "\n";
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
cin >> t;
for (int i = 1; i <= t; i++) {
check();
}
return 0;
}
| 8 | CPP |
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) | 8 | PYTHON3 |
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import defaultdict
def gift():
for _ in range(t):
n,k = list(map(int,input().split()))
array = input()
dic = defaultdict(lambda:0)
dicLis = []
curr = 0
win = 0
score = 0
for i in range(n):
if array[i]=="W":
if win>0:
score+=2
else:
score+=1
win += 1
dicLis.append(curr)
curr=0
else:
win = 0
curr+=1
dicLis.append(curr)
for i in range(1,len(dicLis)-1):
if dicLis[i]:
dic[dicLis[i]]+=1
itemRino = sorted(list(dic.items()))
for ele in itemRino:
gap, count = ele
while count:
if k>=gap:
score += gap*2+1
else:
score += k*2
count-=1
k -= gap
#print(gap,k,score)
if k<=0:
break
if k<=0:
break
if k>0:
if len(dicLis)>1 and dicLis[-1]>0:
score += 2*(min(k,dicLis[-1]))
k-=dicLis[-1]
if k>0:
if len(dicLis)>1:
score += 2*(min(k,dicLis[0]))
k-=dicLis[0]
else:
score += 2*(min(k,dicLis[0]))-1
yield score
if __name__ == '__main__':
t= int(input())
ans = gift()
print(*ans,sep='\n')
#"{} {} {}".format(maxele,minele,minele)
| 8 | PYTHON3 |
#include <CodeforcesSolutions.h>
#include <ONLINE_JUDGE <solution.cf(contestID = "1427",questionID = "A",method = "GET")>.h>
"""
Author : thekushalghosh
Team : CodeDiggers
I prefer Python language over the C++ language :p :D
Visit my website : thekushalghosh.github.io
"""
import sys,math,cmath,time,collections
start_time = time.time()
##########################################################################
################# ---- THE ACTUAL CODE STARTS BELOW ---- #################
def solve():
n,k = invr()
s = list(insr())
ww = 0
if "W" not in s:
if k == 0:
c = 0
else:
c = (2 * min(k,len(s))) - 1
elif s.count("W") == 1:
if k == 0:
c = 1
else:
c = (2 * min(k + 1,len(s))) - 1
else:
q = s.index("W")
s.reverse()
w = s.index("W")
s.reverse()
c = 0
qw = []
for i in range(q,len(s) - w):
if s[i] == "L":
c = c + 1
elif c > 0:
qw.append(c)
c = 0
qw.sort(reverse = True)
ww = 0
while qw and k > 0:
qq = qw.pop()
if k >= qq:
k = k - qq
ww = ww + (qq * 2) + 1
else:
ww = ww + (k * 2)
k = 0
ww = ww + (k * 2)
c = 0
for i in range(len(s)):
if s[i] == "W":
if i != 0 and s[i - 1] == "W":
c = c + 2
else:
c = c + 1
print(min((2 * len(s)) - 1,c + ww))
################## ---- THE ACTUAL CODE ENDS ABOVE ---- ##################
##########################################################################
def main():
global tt
if not ONLINE_JUDGE:
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
t = 1
t = inp()
for tt in range(1,t + 1):
solve()
if not ONLINE_JUDGE:
print("Time Elapsed :",time.time() - start_time,"seconds")
sys.stdout.close()
#---------------------- USER DEFINED INPUT FUNCTIONS ----------------------#
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
return(input().strip())
def invr():
return(map(int,input().split()))
#------------------ USER DEFINED PROGRAMMING FUNCTIONS ------------------#
def counter(a):
q = [0] * max(a)
for i in range(len(a)):
q[a[i] - 1] = q[a[i] - 1] + 1
return(q)
def counter_elements(a):
q = dict()
for i in range(len(a)):
if a[i] not in q:
q[a[i]] = 0
q[a[i]] = q[a[i]] + 1
return(q)
def string_counter(a):
q = [0] * 26
for i in range(len(a)):
q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
return(q)
def factorial(n,m = 1000000007):
q = 1
for i in range(n):
q = (q * (i + 1)) % m
return(q)
def factors(n):
q = []
for i in range(1,int(n ** 0.5) + 1):
if n % i == 0: q.append(i); q.append(n // i)
return(list(sorted(list(set(q)))))
def prime_factors(n):
q = []
while n % 2 == 0: q.append(2); n = n // 2
for i in range(3,int(n ** 0.5) + 1,2):
while n % i == 0: q.append(i); n = n // i
if n > 2: q.append(n)
return(list(sorted(q)))
def transpose(a):
n,m = len(a),len(a[0])
b = [[0] * n for i in range(m)]
for i in range(m):
for j in range(n):
b[i][j] = a[j][i]
return(b)
def power_two(x):
return (x and (not(x & (x - 1))))
def ceil(a, b):
return -(-a // b)
def seive(n):
a = [1]
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p ** 2,n + 1, p):
prime[i] = False
p = p + 1
for p in range(2,n + 1):
if prime[p]:
a.append(p)
return(a)
#-----------------------------------------------------------------------#
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
#import io,os
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
input = sys.stdin.readline
main() | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
int T, N, K;
cin >> T;
while (T--) {
cin >> N >> K;
string s;
cin >> s;
int i = 0, ws = 0, wstreaks = 0;
vector<int> scount(s.size());
while (i < s.size() && s[i] == 'L') ++i;
while (i < s.size()) {
while (i < s.size() && s[i] == 'W') ++i, ++ws;
++wstreaks;
int lstreak = 0;
while (i < s.size() && s[i] == 'L') ++i, ++lstreak;
if (i != s.size()) ++scount[lstreak];
}
for (int i = 1; i < scount.size(); ++i) {
int count = min(scount[i], K / i);
K -= count * i;
wstreaks -= count;
ws += count * i;
}
ws += min(K, (int)s.size() - ws);
if (wstreaks == 0 && ws) wstreaks = 1;
int score = 2 * ws - wstreaks;
cout << score << '\n';
}
}
| 8 | CPP |
import array
T=int(input())
for Tid in range(T):
n,k=map(int,input().split())
a=input()
def c1():
sum=0
tmp=k
for i in range(n):
if a[i]=='W':
sum+=2
else:
if tmp!=0:
tmp,sum=tmp-1,sum+2
#print('ANS=%d' % sum)
return sum
def c2():
sum,la=0,-(1<<30)
b=[]
for i in range(n):
if a[i]=='W':
if i==0 or a[i-1]=='L':
sum+=1
if i!=0 and a[i-1]=='L' and la>0:
b.append(la)
la=0
else:
la=la+1
tmp=k
b=sorted(b)
#print(b,tmp)
for i in range(len(b)):
if tmp>=b[i]:
tmp-=b[i]
sum-=1
return max(sum,1)
print(max(c1()-c2(),0)) | 8 | PYTHON3 |
import sys,io,os
z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#z=sys.stdin.readline
o=[]
for _ in range(int(z())):
n,k=map(int,z().split())
s=z().strip()
b=c=p=r=0
l=[]
for i in s:
if i%2:
if b:
if c:l.append(c);c=0
else:b=1
r+=1+(i==p)
elif b:c+=1
p=i
l.sort(reverse=True)
while l:
v=l.pop()
if k>=v:
k-=v
r+=2*v+1
else:
break
if r==0:r=-1
r+=2*k
o.append(str(min(max(r,0),2*n-1)))
print('\n'.join(o)) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
;
int t, n, k, cnt;
string boi;
cin >> t;
while (t--) {
cin >> n >> k;
cin >> boi;
cnt = 0;
for (int i = 0; i < n; i++) cnt += (boi[i] == 'W');
if (cnt == 0) {
cout << max(2 * k - 1, 0) << '\n';
continue;
}
if (n == 1 and k == 1 and boi == "L") {
cout << "1\n";
continue;
}
if (n == 1 and boi == "L") {
cout << "0\n";
continue;
}
vector<int> zero;
int temp = 1, sum = 0, anfang = 0, schluss = 0;
if (boi[0] == 'L') {
for (int i = 0; i < n; i++)
if (boi[i] == 'L')
anfang++;
else
break;
}
if (boi[n - 1] == 'L') {
for (int i = n - 1; i >= 0; i--)
if (boi[i] == 'L')
schluss++;
else
break;
}
if (boi[anfang] == 'W') sum++;
for (int i = 1 + anfang; i < n - schluss; i++) {
if (boi[i] == boi[i - 1] and boi[i] == 'L') {
temp++;
} else if (boi[i] == 'W' and boi[i - 1] == 'L') {
zero.push_back(temp);
temp = 1;
}
if (boi[i] == 'W') {
sum++;
if (i != 0 and boi[i - 1] == 'W') sum++;
}
}
for (int i = 0; i < zero.size(); i++) {
zero[i] = 2 * zero[i] + 1;
}
if (anfang > schluss) swap(anfang, schluss);
sort(zero.begin(), zero.end());
bool a = false, s = false;
for (auto it : zero) {
if (k == 0) break;
if (k >= it / 2) {
k -= it / 2;
sum += it;
} else {
sum += 2 * k;
k = 0;
}
}
if (!a) {
if (k >= anfang) {
k -= anfang;
sum += 2 * anfang;
} else {
sum += 2 * k;
k = 0;
}
a = true;
}
if (!s) {
if (k >= schluss) {
k -= schluss;
sum += 2 * schluss;
} else {
sum += 2 * k;
k = 0;
}
s = true;
}
cout << sum << '\n';
}
return 0;
}
| 8 | CPP |
#! /usr/bin/python3
import os
import sys
from io import BytesIO, IOBase
def main():
for _ in range(int(input())):
n, k = map(int, input().split())
s = input()
ind = []
ans = 0
for i in range(n):
if s[i] == 'W':
ind.append(i)
if i > 0 and s[i-1] == 'W':
ans += 1
ans += 1
if k == 0:
print(ans)
elif len(ind) == 0:
print(min(n, k) * 2 - 1)
else:
gaps = []
for i in range(len(ind) - 1):
gaps.append(ind[i+1] - ind[i] - 1)
gaps.sort()
k = min(k, n - len(ind))
ans += 2 * k
for i in gaps:
if i > 0:
if k >= i:
ans += 1
k -= i
else:
break
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| 8 | PYTHON3 |
import sys
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
t=int(input())
for _ in range(t):
n,k=[int(x) for x in input().split()]
s=list(input())
startGroup=[]
endGroup=[]
LGroups=[]
currLGroup=[]
isStart=False
isEnd=False
for i in range(n):
if i==0:
isStart=True
if s[i]=='W':
if len(currLGroup)>0:
if isStart:
startGroup=currLGroup
else:
LGroups.append(currLGroup)
isStart=False
currLGroup=[]
else:
currLGroup.append(i)
if len(currLGroup)>0:
endGroup=currLGroup
finalLCount=max(s.count('L')-k,0)
# print('finalLCount:{}'.format(finalLCount))##
# print('startG:{} endG:{}'.format(startGroup,endGroup))
s2=['W']*n
if finalLCount>0:
for i in startGroup:
s2[i]='L'
finalLCount-=1
if finalLCount==0:
break
if finalLCount>0:
for j in range(len(endGroup)-1,-1,-1):
s2[endGroup[j]]='L'
finalLCount-=1
if finalLCount==0:
break
if finalLCount>0:
LGroups.sort(key=lambda x:len(x),reverse=True)
for g in LGroups:
for i in g:
s2[i]='L'
finalLCount-=1
if finalLCount==0:
break
if finalLCount==0:
break
# print(s2) ####
ans=0
for i in range(n):
if s2[i]=='W':
ans+=1
if i>0 and s2[i-1]=='W':
ans+=1
print(ans) | 8 | PYTHON3 |
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
import time
start_time = time.time()
import collections as col
import math
from functools import reduce
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
"""
max number of wins is sum (2*len-1) where len = len of set of Ws
if we add a W between two Ls, we gain one
if we add a W between W and L or between L and W, we gain two
if we add a W between W and W, we gain three
More generally, we want to target the shortest gaps between Ws and fill them up
BUT we can create
So greedily we want to find WLW, then WL, then just L
WWLLLLLWWLWLL
"""
def solve():
N, K = getInts()
S = listStr()
if N == 1:
if K == 1 or S[0] == 'W':
return 1
return 0
gaps = []
curr = 0
wins = 0
for j in range(N):
if S[j] == 'L':
curr += 1
elif curr > 0:
gaps.append(curr)
curr = 0
if S[j] == 'W':
wins += 1
if j > 0 and S[j-1] == 'W':
wins += 1
if K == 0:
return wins
if S[j] == 'L':
gaps.append(curr)
#print(gaps)
pref = 0
suff = 0
#print("Win",wins)
if not gaps:
return wins
if len(gaps) == 1:
if S[0] == 'W' and S[-1] == 'W':
pass
else:
if S[0] == 'W' or S[-1] == 'W':
change = min(K,gaps[0])
wins += 2*change
return wins
return 2*K-1
if S[0] == 'L':
pref = gaps[0]
gaps = gaps[1:]
if S[-1] == 'L':
suff = gaps[-1]
gaps = gaps[:-1]
gaps.sort(reverse=True)
while K and gaps:
x = gaps.pop()
change = min(K,x)
if change < x:
wins += 2*change
else:
wins += 2*change + 1
K -= change
if K:
change = min(K,pref+suff)
wins += 2*change
K -= change
return wins
for _ in range(getInt()):
print(solve())
| 8 | PYTHON3 |
for _ in range(int(input())):
a,b = map(int,input().split())
s = input()
if s=="L"*a:
if b:
print(b*2-1)
else:print(0)
elif s=="W"*a:
print(a*2-1)
else:
ans =0
fst,lst = -1,-1
if s[0]=="W":
ans+=1
fst =0
lst =0
for i in range(1,a):
if s[i]=="W":
if fst ==-1:
fst =i
if s[i-1]=="W":
ans+=1
ans+=1
lst = i
if b==0:
print(ans)
continue
k = s[fst:lst+1].split("W")
k.sort()
for i in k:
if len(i):
if b>=len(i):
ans+=len(i)*2 +1
b-=len(i)
else:
ans+=b*2
b=0
if b==0:
break
ans+=min(b,fst+a-lst-1)*2
print(ans) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM =
chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
const long long MOD = 1e9 + 7;
const long long INF = 1e9 + 8;
const double pi = 3.14159265359;
long long binpow(long long a, long long b, long long m) {
a %= m;
long long res = 1;
while (b > 0) {
if (b & 1) res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
long long inverse(long long x) { return binpow(x, MOD - 2, MOD); }
void solve() {
long long n, k;
cin >> n >> k;
string s;
cin >> s;
long long ans = 0;
vector<long long> a, b;
for (long long i = 0; i < n; i++) {
if (s[i] == 'W') {
a.push_back(i);
ans += 1 + (i > 0 && s[i - 1] == s[i]);
}
}
long long loss = 0;
while (s.size() > 0 && s.back() == 'L') {
s.pop_back();
loss++;
}
reverse((s).begin(), (s).end());
while (s.size() > 0 && s.back() == 'L') {
s.pop_back();
loss++;
}
if (a.empty()) {
cout << max(0LL, 2 * k - 1) << endl;
return;
}
for (long long i = 0; i + 1 < a.size(); i++) {
if (a[i + 1] - a[i] > 1) b.push_back(a[i + 1] - a[i] - 1);
}
sort((b).begin(), (b).end());
for (auto i : b) {
if (i <= k)
ans += 2 * i + 1, k -= i;
else
ans += 2 * k, k -= k;
}
ans += 2 * min(k, loss);
cout << ans << endl;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
long long t;
cin >> t;
while (t--) solve();
cerr << "Time elapsed : " << 1.0 * clock() / CLOCKS_PER_SEC << " sec \n ";
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
void NITRO() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
const long long N = 1e+5 + 1111;
const long long MOD = 1e7;
const long long INF = 1e+9 + 12345678;
void SOLVE() {
int n, k, lose = 0, l = -1, s = 0;
string word;
cin >> n >> k >> word;
vector<int> v;
for (int i = 0; i < n; i++) {
if (word[i] == 'W') {
s += 2;
if (l != -1) v.push_back(i - l);
l = -1;
} else {
lose++;
if (word[i - 1] == 'W') {
l = i;
}
}
}
if (lose == n) {
if (k == 0)
cout << 0 << '\n';
else
cout << k * 2 - 1 << '\n';
} else if (k >= lose) {
cout << n * 2 - 1 << '\n';
} else {
s += k * 2;
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
while (!v.empty()) {
if (v.back() <= k) {
k -= v.back();
v.pop_back();
} else
break;
}
cout << s - v.size() - 1 << '\n';
}
}
int main() {
NITRO();
int times = 1;
cin >> times;
for (int i = 1; i <= times; i++) {
SOLVE();
}
return 0;
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
bool f = true;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'W') f = false;
}
if (f) {
cout << max(0, (k - 1) * 2 + 1) << endl;
continue;
}
vector<int> sp;
int start = 1e6;
int finish = -1;
int total = 0;
int l = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'W') {
start = min(start, i);
finish = max(finish, i);
total++;
if (i && s[i - 1] == 'W') total++;
} else
l++;
}
k = min(l, k);
int cur = 0;
for (int i = start + 1; i <= finish; i++) {
if (s[i] == 'W') {
if (cur) sp.push_back(cur);
cur = 0;
} else {
cur++;
}
}
sort(sp.begin(), sp.end());
for (int i = 0; i < sp.size(); i++) {
if (k >= sp[i]) {
total += 2 * (sp[i]) + 1;
k -= sp[i];
}
}
total += k * 2;
cout << total << endl;
}
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int NN = 100100;
char s[NN];
int n, k;
vector<int> rec[NN];
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &k);
scanf("%s", s + 1);
int numw = 0;
for (int i = 1; i <= n; i++) {
rec[i].clear();
numw += (s[i] == 'W');
}
if (numw == 0) {
printf("%d\n", max(0, 2 * k - 1));
continue;
}
int last = 0;
for (int i = 1; i <= n; i++) {
if (s[i] == 'L' && (s[i - 1] == 'W')) {
last = i;
}
if (s[i] == 'L' && (s[i + 1] == 'W') && last) {
rec[i - last + 1].push_back(last);
}
}
for (int i = 1; i <= n; i++) {
if (k == 0) break;
int up = rec[i].size();
for (int j = 0; j < up; j++) {
if (k == 0) break;
int ll = rec[i][j];
for (int p = 0; p < i; p++) {
if (k == 0) break;
s[ll + p] = 'W';
k--;
}
}
}
if (k) {
for (int i = 1; i <= n; i++) {
if (s[i] == 'L' && s[i - 1] == 'W') {
s[i] = 'W';
k--;
}
if (k == 0) break;
}
}
if (k) {
for (int i = n; i >= 1; i--) {
if (s[i] == 'L' && s[i + 1] == 'W') {
s[i] = 'W';
k--;
}
if (k == 0) break;
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (s[i] == 'W') {
ans += 1;
ans += (s[i - 1] == 'W');
}
}
printf("%d\n", ans);
}
return 0;
}
| 8 | CPP |
for t in range(int(input())):
n,k = map(int,input().split())
h = input()
if k>= h.count("L"):
print(2*n-1)
elif n==0:
print(0)
elif "W" not in h:
print(max(2*k-1,0))
else:
h = h.strip("L")
n = len(h)
score = 0
prev = "L"
i = 0
l = []
while i<n:
if h[i] == "W":
if prev == "L":
prev = "W"
score += 1
else:
score += 2
else:
if prev == "W":
l.append(1)
prev = "L"
else:
l[-1] += 1
i += 1
l.sort()
while l and k>=l[0]:
temp = l.pop(0)
score += 2*temp + 1
k -= temp
score += 2*k
print(score)
| 8 | PYTHON3 |
t = int(input())
for _ in range(t):
n, k = [int(i) for i in input().split()]
S = input()
consL0 = []
consL1 = [] # on edge
consL2 = [] # alone
startW = S[0] == "W"
c = 1 if S[0] == "L" else 0
ans = 1 if S[0] == "W" else 0
for i in range(1, n):
if S[i] == "L":
c += 1
else:
if c > 0:
if startW:
consL0.append(c)
else:
consL1.append(c)
c = 0
startW = True
ans += 1 if S[i-1] == "L" else 2
if c > 0:
if startW:
consL1.append(c)
else:
consL2.append(c)
if k > 0:
consL0.sort()
while(len(consL0) > 0 and k > 0):
l = consL0.pop(0)
if k >= l:
ans += 2 * l + 1
k -= l
else:
ans += 2 * k
k = 0
break
if k > 0:
consL1.sort()
while(len(consL1) > 0 and k > 0):
l = consL1.pop(0)
ans += 2 * min(k, l)
k -= min(k, l)
if k > 0 and len(consL2) > 0:
l = consL2[0]
ans += 2 * min(k, l) - 1
print(ans) | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int gcd(int x, int y) {
if (!y) return x;
return gcd(y, x % y);
}
long long proceed() {
long long n, k, m;
cin >> n >> k;
string s;
cin >> s;
long long i, p;
for (i = 0; i < n; ++i) {
if (s[i] == 'W') {
m = i;
break;
}
}
if (i == n) {
cout << max((long long)0, 1 + 2 * (min(n, k) - 1)) << endl;
} else {
long long j, indx, cnt = 0;
vector<pair<long long, long long>> v;
p = m;
for (j = i + 1; j < n; ++j) {
if (s[j] == 'L') {
if (s[j - 1] == 'W') indx = j;
++cnt;
} else {
p = j;
if (cnt) v.push_back(make_pair(cnt, indx));
cnt = 0;
}
}
sort(v.begin(), v.end());
for (i = 0; i < v.size(); ++i) {
for (j = v[i].second; j < v[i].first + v[i].second && k > 0; ++j) {
s[j] = 'W';
--k;
}
}
next:
if (k) {
for (i = m - 1; i >= 0 && k > 0; --i) {
s[i] = 'W';
--k;
}
}
if (k) {
for (i = p + 1; i < n && k > 0; ++i) {
s[i] = 'W';
--k;
}
}
long long ans;
s[0] == 'W' ? ans = 1 : ans = 0;
for (i = 1; i < n; ++i) {
if (s[i] == 'W') {
s[i - 1] == 'W' ? ans += 2 : ++ans;
}
}
cout << ans << endl;
}
return 0;
}
int main() {
int t = 1, i = 0;
cin >> t;
while (t--) {
proceed();
}
return 0;
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
int score(string &s, int &n) {
int ans = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') {
if (!i || s[i - 1] != 'W') {
ans++;
} else {
ans += 2;
}
}
}
return ans;
}
void solve() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
if (!k) {
cout << score(s, n) << "\n";
return;
}
vector<int> pos;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') {
pos.push_back(i);
}
}
if (pos.empty()) {
cout << min(2 * k - 1, 2 * n - 1) << "\n";
return;
}
if ((int)pos.size() + k >= n) {
cout << 2 * n - 1 << "\n";
return;
}
if (pos.size() == 1) {
cout << min(2 * (k + 1) - 1, 2 * n - 1) << "\n";
return;
}
vector<vector<int> > v;
for (int i = 1; i < pos.size(); i++) {
if (pos[i] - pos[i - 1] > 1) {
vector<int> a = {pos[i] - pos[i - 1] - 1, pos[i - 1], pos[i]};
v.push_back(a);
}
}
sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++) {
if (k >= v[i][0]) {
k -= v[i][0];
for (int j = v[i][1] + 1; j < v[i][2]; j++) {
s[j] = 'W';
}
} else {
int j = v[i][1] + 1;
while (k--) {
s[j] = 'W';
j++;
}
cout << score(s, n) << "\n";
return;
}
}
if (k) {
for (int i = pos.back() + 1; i < n; i++) {
if (k) {
s[i] = 'W';
k--;
} else {
cout << score(s, n) << "\n";
return;
}
}
}
if (k) {
for (int i = pos.front() - 1; i >= 0; i--) {
if (k) {
s[i] = 'W';
k--;
} else {
cout << score(s, n) << "\n";
return;
}
}
}
cout << score(s, n) << "\n";
return;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| 8 | CPP |
t = int(input())
for test_case in range(t):
n, k = [int(x) for x in input().split()]
s = input()
res = 0
zapol = []
probeli = []
i = 0
torf = False
coins = 0
if n == 1:
if s[0] == 'W':
print()
print(1)
print()
else:
if k == 0:
print()
print(0)
print()
else:
print()
print(1)
print()
continue
while i < n:
if i == 0:
if s[i] == "L":
probeli.append([i])
torf = False
else:
zapol.append([i])
torf = True
if i == n - 1:
if s[i] == 'L':
if torf == False:
probeli[-1].append(i)
else:
probeli.append([i, i])
zapol[-1].append(i - 1)
else:
if torf == True:
zapol[-1].append(i)
else:
zapol.append([i, i])
probeli[-1].append(i - 1)
elif i > 0:
if torf == True and s[i] == 'L':
probeli.append([i])
zapol[-1].append(i - 1)
torf = False
elif torf == False and s[i] == 'W':
torf = True
zapol.append([i])
probeli[-1].append(i - 1)
if s[i] == 'W':
coins += 1
i += 1
probeli2 = []
if k >= n - coins:
print()
print(n*2 - 1)
print()
continue
for i in probeli:
probeli2.append(i)
probeli3 = []
if coins == 0:
print()
print(k*2 - 1 if k > 0 else 0)
print()
continue
kkk = 2
if probeli2[0][0] == 0:
kkk -= 1
if probeli[-1][1] == n - 1:
kkk -= 1
if len(probeli2) > 2:
if probeli2[0][0] == 0:
probeli2.pop(0)
if probeli2[-1][1] == n - 1:
probeli2.pop(-1)
elif len(probeli2) == 1 and kkk == 1:
print()
print((coins + k) * 2 - 1)
print()
continue
elif len(probeli2) == 2 and kkk == 0:
print()
print((coins + k) * 2 - 1)
print()
continue
elif len(probeli2) == 2 and kkk != 0:
if probeli2[0][0] == 0:
probeli2.pop(0)
if probeli2[-1][1] == n - 1:
probeli2.pop(-1)
for i in range(len(probeli2)):
probeli3.append(probeli2[i][1] - probeli2[i][0] + 1)
probeli3.sort()
lenprob2 = len(probeli3)
k2 = k
for i in range(lenprob2):
if k >= probeli3[i]:
k -= probeli3[i]
lenprob2 -= 1
else:
break
res = (coins + k2) * 2 - lenprob2 - 1
print()
print(res)
print() | 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
template <class T>
using TMatrix = vector<vector<T>>;
template <class T>
using TVector = vector<T>;
using TString = string;
void read(int& x) { scanf("%i", &x); }
void write(const int x) { printf("%i", x); }
void read(long long& x) { scanf("%lli", &x); }
void write(const long long& x) { printf("%lli", x); }
void read(double& x) { scanf("%lf", &x); }
void write(const double& x) { printf("%lf", x); }
void read(char& c, bool whiteSpaces = false) {
while (1) {
c = getchar();
if (whiteSpaces || !isspace(c)) {
break;
}
}
}
void write(const char c) { printf("%c", c); }
void read(TString& result, bool untilEol = false) {
result.clear();
char c;
if (!untilEol) {
while (1) {
c = getchar();
if (!isspace(c)) break;
}
result.push_back(c);
}
while (1) {
c = getchar();
if (c == '\n' || (!untilEol && isspace(c))) break;
result.push_back(c);
}
}
void write(const TString& s) { printf("%s", s.c_str()); }
void writeYES(const bool condition) {
printf("%s\n", condition ? "YES" : "NO");
}
void writeYes(const bool condition) {
printf("%s\n", condition ? "Yes" : "No");
}
template <class T>
void writeIf(const bool condition, const T& forTrue, const T& forFalse) {
cout << (condition ? forTrue : forFalse) << endl;
}
template <class T1, class T2>
void read(pair<T1, T2>& x) {
read(x.first);
read(x.second);
}
template <class T1, class T2>
void write(pair<T1, T2>& x) {
write(x.first);
write(' ');
write(x.second);
}
template <class T>
void writeln(const T& x) {
write(x);
write('\n');
}
template <class T1, class T2>
void read(T1& x1, T2& x2) {
read(x1);
read(x2);
}
template <class T1, class T2, class T3>
void read(T1& x1, T2& x2, T3& x3) {
read(x1);
read(x2);
read(x3);
}
template <class T1, class T2, class T3, class T4>
void read(T1& x1, T2& x2, T3& x3, T4& x4) {
read(x1);
read(x2);
read(x3);
read(x4);
}
template <class T1, class T2, class T3, class T4, class T5>
void read(T1& x1, T2& x2, T3& x3, T4& x4, T5& x5) {
read(x1);
read(x2);
read(x3);
read(x4);
read(x5);
}
template <class T1, class T2, class T3, class T4, class T5, class T6>
void read(T1& x1, T2& x2, T3& x3, T4& x4, T5& x5, T6& x6) {
read(x1);
read(x2);
read(x3);
read(x4);
read(x5);
read(x6);
}
template <class T1, class T2, class T3, class T4, class T5, class T6, class T7>
void read(T1& x1, T2& x2, T3& x3, T4& x4, T5& x5, T6& x6, T7& x7) {
read(x1);
read(x2);
read(x3);
read(x4);
read(x5);
read(x6);
read(x7);
}
namespace NMatrix {
template <class T>
void Read(TMatrix<T>& matrix, int n = -1, int m = -1) {
if (n == -1) {
read(n, m);
} else if (m == -1) {
m = n;
}
matrix.clear();
matrix.resize(n, TVector<T>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
read(matrix[i][j]);
}
}
}
template <class T>
void Write(const TMatrix<T>& v, const TString del = " ") {
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++) {
cout << v[i][j];
if (j < v[i].size() - 1) {
cout << del;
}
}
cout << endl;
}
}
template <class T>
T Sum(const TMatrix<T>& matrix) {
T result = 0;
for (const auto& row : matrix) {
for (const auto& elem : row) {
result += elem;
}
}
return result;
}
template <class T>
TMatrix<T> Sum(const TMatrix<T>& matrix1, const TMatrix<T>& matrix2) {
TMatrix<T> result(matrix1.size(), TVector<T>(matrix1[0].size()));
for (size_t i = 0; i < matrix1.size(); ++i) {
for (size_t j = 0; j < matrix1[i].size(); ++j) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return move(result);
}
template <class T>
TMatrix<T> Transpose(const TMatrix<T>& matrix) {
TMatrix<T> result(matrix[0].size(), TVector<T>(matrix.size()));
for (size_t i = 0; i < matrix.size(); ++i) {
for (size_t j = 0; j < matrix[i].size(); ++j) {
result[j][i] = matrix[i][j];
}
}
return move(result);
}
} // namespace NMatrix
namespace NVector {
template <class T>
void Read(TVector<T>& v, int length = -1) {
if (length == -1) {
read(length);
}
v.resize(length);
for (auto& elem : v) {
read(elem);
}
}
template <class T>
void Write(const TVector<T>& v, TString del = " ", bool needEndl = true) {
for (int i = 0; i < v.size(); i++) {
cout << v[i];
if (i < v.size() - 1) {
cout << del;
}
}
if (needEndl) {
cout << endl;
}
}
template <class T>
TVector<T> Filter(const TVector<T>& v, std::function<bool(T)> filter) {
TVector<T> result;
for (const auto& elem : v) {
if (filter(elem)) {
result.push_back(elem);
}
}
return move(result);
}
template <class T>
T Max(const TVector<T>& v) {
return *max_element(v.begin(), v.end());
}
template <class T>
void Sort(TVector<T>& v) {
sort(v.begin(), v.end());
}
template <class T>
void SortR(TVector<T>& v) {
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
}
template <class T>
void Reverse(TVector<T>& v) {
reverse(v.begin(), v.end());
}
template <class T>
T Min(const TVector<T>& v) {
return *min_element(v.begin(), v.end());
}
template <class T>
T Sum(const TVector<T>& v) {
T result = 0;
for (const auto& elem : v) {
result += elem;
}
return result;
}
template <class T>
T Mult(const TVector<T>& v) {
T result = 1;
for (const auto& elem : v) {
result *= elem;
}
return result;
}
template <class T>
TVector<int> FromInt(T number) {
TVector<int> v;
while (number) {
v.push_back(number % 10);
number /= 10;
}
reverse(v.begin(), v.end());
return move(v);
}
template <class T>
T ToInt(const TVector<int>& v) {
T ans = 0;
for (const auto e : v) {
ans = ans * 10 + e;
}
return ans;
}
template <class T>
T Mex(const TVector<T>& v) {
unordered_set<T> s(v.begin(), v.end());
T value;
for (value = 1; s.find(value) != s.end(); value += 1) {
}
return value;
}
template <class T>
bool Contains(const TVector<T>& v, const T& searchedElem) {
for (const auto& elem : v) {
if (elem == searchedElem) {
return true;
}
}
return false;
}
} // namespace NVector
namespace NMath {
template <class T>
T Gcd(T x, T y) {
while (x) {
y %= x;
swap(x, y);
}
return y;
}
template <class T>
T Lcm(T x, T y) {
return (x / Gcd(x, y)) * y;
}
template <class T>
T Gcd(const vector<T>& v) {
T ans = v.front();
for (const auto& elem : v) {
ans = Gcd(ans, elem);
}
return ans;
}
template <class T>
T Lcm(const vector<T>& v) {
T ans = v.front();
for (const auto& elem : v) {
ans = Lcm(ans, elem);
}
return ans;
}
int GcdEx(const int a, const int b, int& x, int& y) {
if (!a) {
x = 0;
y = 1;
return b;
}
int x1, y1;
int d = GcdEx(b % a, a, x1, y1);
x = y1 - (b / a) * x1;
y = x1;
return d;
}
int CalcInverseNumber(const int number, const int mod) {
int x, y;
int g = GcdEx(number, mod, x, y);
if (g != 1) {
return -1;
}
return x = (x % mod + mod) % mod;
}
template <class T>
T Factorial(T n) {
T result = 1;
while (n > 0) {
result *= n--;
}
}
template <class T>
T FactorialWithMod(T n, T mod) {
if (n >= mod) {
return 0;
}
T result = 1;
while (n > 0) {
result = (result * n) % mod;
--n;
}
return result;
}
template <class T1, class T2>
T1 BinPow(T1 value, T2 extent) {
T1 res = 1;
while (extent > 0) {
if (extent & 1) {
res *= value;
}
extent >>= 1;
value *= value;
}
return res;
}
template <class T1, class T2>
T1 BinPowWithMod(T1 value, T2 extent, T1 mod) {
T1 res = 1;
value %= mod;
while (extent > 0) {
if (extent & 1) {
res = (value * res) % mod;
}
extent >>= 1;
value = (value * value) % mod;
}
return res;
}
template <class T>
bool IsPrime(T value) {
for (T i = 2; i * i <= value; ++i) {
if (value % i == 0) {
return false;
}
}
return true;
}
template <class T>
T Min(const T& a, const T& b) {
return a < b ? a : b;
}
template <class T>
T Max(const T& a, const T& b) {
return a > b ? a : b;
}
template <class T>
T Abs(const T& value) {
return value >= 0 ? value : -value;
}
TVector<int> Factorize(int value) {
TVector<int> res;
for (int i = 2; i * i <= value; i++) {
while (value % i == 0) {
res.push_back(i);
value /= i;
}
}
if (value > 1) {
res.push_back(value);
}
return res;
}
template <class T>
TVector<int> ToKSystem(T value, const int numberOfSystem) {
TVector<int> result;
while (value > 0) {
result.push_back(value % numberOfSystem);
value /= numberOfSystem;
}
if (result.empty()) result.push_back(0);
reverse(result.begin(), result.end());
return result;
}
template <class T>
T FromKSystem(const TVector<int> value, const int numberOfSystem) {
T result = 0;
T mult = 1;
for (int i = value.size() - 1; i >= 0; --i) {
result += mult * value[i];
mult *= numberOfSystem;
}
return result;
}
double Log(const double a, const double b) { return log(b) / log(a); }
} // namespace NMath
namespace NString {
TVector<TString> Split(const TString& value, const char delimiter = ' ',
bool skipEmpty = false) {
TString current = "";
TVector<TString> result;
for (size_t i = 0; i <= value.size(); i++) {
if (i == value.size() || value[i] == delimiter) {
if (!skipEmpty || !current.empty()) {
result.push_back(current);
current.clear();
}
} else {
current.push_back(value[i]);
}
}
return move(result);
}
TString ToString(long long value) {
TString result;
bool isNegative = false;
if (value < 0) {
isNegative = true;
value = -value;
}
if (!value) {
result.push_back('0');
}
while (value > 0) {
result.push_back((value % 10) + '0');
value /= 10;
}
if (isNegative) {
result.push_back('-');
}
reverse(result.begin(), result.end());
return result;
}
TString ToString(const int value) { return ToString(1ll * value); }
long long ToLong(const TString& value) {
long long result = 0;
bool isNegative = false;
auto it = value.begin();
if (*it == '-') {
isNegative = true;
it++;
}
for (; it != value.end(); it++) {
result = result * 10 + (*it) - '0';
}
if (isNegative) {
result = -result;
}
return result;
}
int ToInt(const TString& value) { return static_cast<int>(ToLong(value)); }
TString ToUpper(const TString& value) {
TString result = value;
for (auto& c : result) {
c = toupper(c);
}
return result;
}
TString ToLower(const TString& value) {
TString result = value;
for (auto& c : result) {
c = tolower(c);
}
return result;
}
bool StartsWith(const TString& first, const TString& second) {
if (second.size() > first.size()) return false;
return first.substr(0, second.size()) == second;
}
bool EndsWith(const TString& first, const TString& second) {
if (second.size() > first.size()) return false;
return first.substr(first.size() - second.size()) == second;
}
} // namespace NString
int solve();
int main(int argc, char* argv[]) {
return solve();
return 0;
}
int solve() {
int t;
read(t);
while (t--) {
int n, k;
read(n, k);
TVector<char> v;
NVector::Read(v, n);
TVector<pair<int, int>> ps;
ps.reserve(n);
for (int i = 0; i < v.size(); i++) {
if (v[i] == 'L') {
if (ps.empty() || v[i - 1] == 'W') {
ps.push_back({1, i});
} else {
ps[ps.size() - 1].first++;
}
}
}
NVector::Sort(ps);
for (int i = 0; i < ps.size() && k; i++) {
if (ps[i].second == 0 || ps[i].second + ps[i].first == v.size()) {
continue;
}
for (int j = ps[i].second; k && j < ps[i].second + ps[i].first; j++) {
k--;
v[j] = 'W';
}
}
for (int i = 1; k && i < v.size(); i++) {
if (v[i] == 'L' && v[i - 1] == 'W') {
k--;
v[i] = 'W';
}
}
for (int i = v.size() - 2; k && i >= 0; i--) {
if (v[i] == 'L' && v[i + 1] == 'W') {
k--;
v[i] = 'W';
}
}
for (int i = v.size() - 1; k && i >= 0; i--) {
if (v[i] == 'L') {
k--;
v[i] = 'W';
}
}
int ans = (v[0] == 'W' ? 1 : 0);
for (int i = 1; i < v.size(); i++) {
if (v[i] == 'W') {
ans++;
if (v[i - 1] == 'W') {
ans++;
}
}
}
cout << ans << '\n';
}
return 0;
}
| 8 | CPP |
def main():
n, k = map(int, input().split())
line = input()
was = False
prev = False
res = 0
before = 0
spare_sizes = []
sz = 0
for i in line:
if not was:
if i == "L":
before += 1
else:
was = True
if was:
if i == "L":
sz += 1
else:
if sz > 0:
spare_sizes.append(sz)
sz = 0
if i == "W":
if prev:
res += 2
else:
res += 1
prev = True
else:
prev = False
if was:
before += sz
if res == 0 and k > 0:
res -= 1
spare_sizes = sorted(spare_sizes)
for i in range(len(spare_sizes)):
if spare_sizes[i] > k:
res += 2*k
k = 0
break
else:
res += 2*(spare_sizes[i])
k -= spare_sizes[i]
res += 1
if k == 0:
break
res += 2*min(k, before)
print(res)
if __name__ == '__main__':
t = int(input())
for i in range(t):
main()
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
int wins = 0, lose = 0, w_s = 0;
string s;
vector<int> l_s;
cin >> s;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') {
wins++;
if (i == 0 || s[i - 1] == 'L') w_s++;
}
if (s[i] == 'L') {
lose++;
if (i == 0 || s[i - 1] == 'W') {
l_s.push_back(0);
}
l_s.back()++;
}
}
if (k >= lose) {
cout << 2 * n - 1 << "\n";
continue;
}
if (wins == 0) {
if (k == 0)
cout << 0 << "\n";
else
cout << 2 * k - 1 << "\n";
continue;
}
if (s[0] == 'L') l_s[0] = 1e9;
if (s[n - 1] == 'L') l_s.back() = 1e9;
sort(l_s.begin(), l_s.end());
wins += k;
for (auto it : l_s) {
if (it > k) break;
k -= it;
w_s--;
}
cout << 2 * wins - w_s << "\n";
}
return 0;
}
| 8 | CPP |
z,zz=input,lambda:list(map(int,z().split()))
fast=lambda:stdin.readline().strip()
zzz=lambda:[int(i) for i in stdin.readline().split()]
szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz())
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac
def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2))
def prime(x):
p=ceil(x**.5)+1
for i in range(2,p):
if (x%i==0 and x!=2) or x==0:return 0
return 1
def dfs(u,visit,graph):
visit[u]=True
for i in graph[u]:
if not visit[i]:
dfs(i,visit,graph)
###########################---Test-Case---#################################
"""
"""
###########################---START-CODING---##############################
num=int(z())
ans=[]
for _ in range( num ):
n,k=zz()
arr=sorted(map(len,fast().strip('L').split('W')))
m=len(arr)+k
while arr and arr[0]<=k:
k-=arr.pop(0)
ans.append((2*min(n,m-1)-len(arr)or 1)-1)
for _ in ans:print(_)
| 8 | PYTHON3 |
import sys
from sys import stdin,stdout
def II(): # to take integer input
return int(stdin.readline())
def IP(): # to take tuple as input
return map(int,stdin.readline().split())
def solve():
n,k=IP()
s=input()
cnt=s.count('W')
if k==0:
ans=0
last='L'
for ele in s:
if ele=='W' and last=='W':
ans+=2
elif ele=='W' and last=='L':
ans+=1
last=ele
print(ans)
return
else:
if cnt==0:
print(1+2*(k-1))
return
else:
new=[0]*n
first,last=2*n,-1
for i in range(n):
new[i]=s[i]
if s[i]=='W':
first=min(first,i)
last=max(last,i)
pq=[]
if first!=last:
llast=first
for i in range(first+1,last+1,1):
if s[i]=='W':
pq.append([i-llast-1,llast])
llast=i
pq.sort()
i=0
nn=len(pq)
#print(pq)
while k>0 and i<nn:
lenn,strt=pq[i]
end=(strt+lenn+1)
for j in range(strt+1,end):
if k>0:
new[j]='W'
k-=1
else:
break
i+=1
if k>0:
if s[last-1]=='W':
for i in range(last+1,n):
if k>0:
new[i]='W'
k-=1
else:
break
for i in range(first-1,-1,-1):
if k>0:
new[i]='W'
k-=1
else:
break
else:
for i in range(first-1,-1,-1):
if k>0:
new[i]='W'
k-=1
else:
break
for i in range(last+1,n):
if k>0:
new[i]='W'
k-=1
else:
break
ans=0
last='L'
for ele in new:
if ele=='W' and last=='W':
ans+=2
elif ele=='W' and last=='L':
ans+=1
last=ele
print(ans)
return
t=II()
for i in range(t):
solve()
#######
#
#
####### # # # #### # # #
# # # # # # # # # # #
# #### # # #### #### # #
###### # # #### # # # # #
# ``````ΒΆ0````1ΒΆ1_```````````````````````````````````````
# ```````ΒΆΒΆΒΆ0_`_ΒΆΒΆΒΆ0011100ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ001_````````````````````
# ````````ΒΆΒΆΒΆΒΆΒΆ00ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0_````````````````
# `````1_``ΒΆΒΆ00ΒΆ0000000000000000000000ΒΆΒΆΒΆΒΆ0_`````````````
# `````_ΒΆΒΆ_`0ΒΆ000000000000000000000000000ΒΆΒΆΒΆΒΆΒΆ1``````````
# ```````ΒΆΒΆΒΆ00ΒΆ00000000000000000000000000000ΒΆΒΆΒΆ_`````````
# ````````_ΒΆΒΆ00000000000000000000ΒΆΒΆ00000000000ΒΆΒΆ`````````
# `````_0011ΒΆΒΆΒΆΒΆΒΆ000000000000ΒΆΒΆ00ΒΆΒΆ0ΒΆΒΆ00000000ΒΆΒΆ_````````
# ```````_ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ00000000000ΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆ00000000ΒΆΒΆ1````````
# ``````````1ΒΆΒΆΒΆΒΆΒΆ000000ΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0000000ΒΆΒΆΒΆ````````
# ```````````ΒΆΒΆΒΆ0ΒΆ000ΒΆ00ΒΆ0ΒΆΒΆ`_____`__1ΒΆ0ΒΆΒΆ00ΒΆ00ΒΆΒΆ````````
# ```````````ΒΆΒΆΒΆΒΆΒΆ00ΒΆ00ΒΆ10ΒΆ0``_1111_`_ΒΆΒΆ0000ΒΆ0ΒΆΒΆΒΆ````````
# ``````````1ΒΆΒΆΒΆΒΆΒΆ00ΒΆ0ΒΆΒΆ_ΒΆΒΆ1`_ΒΆ_1_0_`1ΒΆΒΆ_0ΒΆ0ΒΆΒΆ0ΒΆΒΆ````````
# ````````1ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆ0ΒΆ0_0ΒΆ``100111``_ΒΆ1_0ΒΆ0ΒΆΒΆ_1ΒΆ````````
# ```````1ΒΆΒΆΒΆΒΆ00ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ010ΒΆ``1111111_0ΒΆ11ΒΆΒΆΒΆΒΆΒΆ_10````````
# ```````0ΒΆΒΆΒΆΒΆ__10ΒΆΒΆΒΆΒΆΒΆ100ΒΆΒΆΒΆ0111110ΒΆΒΆΒΆ1__ΒΆΒΆΒΆΒΆ`__````````
# ```````ΒΆΒΆΒΆΒΆ0`__0ΒΆΒΆ0ΒΆΒΆ_ΒΆΒΆΒΆ_11````_0ΒΆΒΆ0`_1ΒΆΒΆΒΆΒΆ```````````
# ```````ΒΆΒΆΒΆ00`__0ΒΆΒΆ_00`_0_``````````1_``ΒΆ0ΒΆΒΆ_```````````
# ``````1ΒΆ1``ΒΆΒΆ``1ΒΆΒΆ_11``````````````````ΒΆ`ΒΆΒΆ````````````
# ``````1_``ΒΆ0_ΒΆ1`0ΒΆ_`_``````````_``````1_`ΒΆ1````````````
# ``````````_`1ΒΆ00ΒΆΒΆ_````_````__`1`````__`_ΒΆ`````````````
# ````````````ΒΆ1`0ΒΆΒΆ_`````````_11_`````_``_``````````````
# `````````ΒΆΒΆΒΆΒΆ000ΒΆΒΆ_1```````_____```_1``````````````````
# `````````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0_``````_````_1111__``````````````
# `````````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ01_`````_11____1111_```````````
# `````````ΒΆΒΆ0ΒΆ0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ1101_______11ΒΆ_```````````
# ``````_ΒΆΒΆΒΆ0000000ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆ0ΒΆΒΆΒΆ1````````````
# `````0ΒΆΒΆ0000000ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ1`````````````
# ````0ΒΆ0000000ΒΆΒΆ0_````_011_10ΒΆ110ΒΆ01_1ΒΆΒΆΒΆ0````_100ΒΆ001_`
# ```1ΒΆ0000000ΒΆ0_``__`````````_`````````0ΒΆ_``_00ΒΆΒΆ010ΒΆ001
# ```ΒΆΒΆ00000ΒΆΒΆ1``_01``_11____``1_``_`````ΒΆΒΆ0100ΒΆ1```_00ΒΆ1
# ``1ΒΆΒΆ00000ΒΆ_``_ΒΆ_`_101_``_`__````__````_0000001100ΒΆΒΆΒΆ0`
# ``ΒΆΒΆΒΆ0000ΒΆ1_`_ΒΆ``__0_``````_1````_1_````1ΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆΒΆ0```
# `_ΒΆΒΆΒΆΒΆ00ΒΆ0___01_10ΒΆ_``__````1`````11___`1ΒΆΒΆΒΆ01_````````
# `1ΒΆΒΆΒΆΒΆΒΆ0ΒΆ0`__01ΒΆΒΆΒΆ0````1_```11``___1_1__11ΒΆ000`````````
# `1ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ1_1_01__`01```_1```_1__1_11___1_``00ΒΆ1````````
# ``ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0`__10__000````1____1____1___1_```10ΒΆ0_```````
# ``0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ1___0000000```11___1__`_0111_```000ΒΆ01```````
# ```ΒΆΒΆΒΆ00000ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ01___1___00_1ΒΆΒΆΒΆ`_``1ΒΆΒΆ10ΒΆΒΆ0```````
# ```1010000ΒΆ000ΒΆΒΆ0100_11__1011000ΒΆΒΆ0ΒΆ1_10ΒΆΒΆΒΆ_0ΒΆΒΆ00``````
# 10ΒΆ000000000ΒΆ0________0ΒΆ000000ΒΆΒΆ0000ΒΆΒΆΒΆΒΆ000_0ΒΆ0ΒΆ00`````
# ΒΆΒΆΒΆΒΆΒΆΒΆ0000ΒΆΒΆΒΆΒΆ_`___`_0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ00000000000000_0ΒΆ00ΒΆ01````
# ΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ_``_1ΒΆΒΆΒΆ00000000000000000000_0ΒΆ000ΒΆ01```
# 1__```1ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ00ΒΆΒΆΒΆΒΆ00000000000000000000ΒΆ_0ΒΆ0000ΒΆ0_``
# ```````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ00000000000000000000010ΒΆ00000ΒΆΒΆ_`
# ```````0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ00000000000000000000ΒΆ10ΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆ0`
# ````````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆ00000000000000000000010ΒΆΒΆΒΆ0011```
# ````````1ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆ0000000000000000000ΒΆ100__1_`````
# `````````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ000000000000000000ΒΆ11``_1``````
# `````````1ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆ00000000000000000ΒΆ11___1_`````
# ``````````ΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆ0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0000000000000000ΒΆ11__``1_````
# ``````````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆ000000000000000ΒΆ1__````__```
# ``````````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0000000000000000__`````11``
# `````````_ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ000ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ000000000000011_``_1ΒΆΒΆΒΆ0`
# `````````_ΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆ000000ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ000000000000100ΒΆΒΆΒΆΒΆ0_`_
# `````````1ΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆ000000000ΒΆΒΆΒΆΒΆΒΆΒΆ000000000ΒΆ00ΒΆΒΆ01`````
# `````````ΒΆΒΆΒΆΒΆΒΆ0ΒΆ0ΒΆΒΆΒΆ0000000000000ΒΆ0ΒΆ00000000011_``````_
# ````````1ΒΆΒΆ0ΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆ000000000000000000000ΒΆ11___11111
# ````````ΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆΒΆ00ΒΆΒΆΒΆΒΆΒΆΒΆ000000000000000000ΒΆ011111111_
# ```````_ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ0000000ΒΆ0ΒΆ00000000000000000ΒΆ01_1111111
# ```````0ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ000000000000000000000000000ΒΆ01___`````
# ```````ΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆ000000000000000000000000000ΒΆ01___1````
# ``````_ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ00000000000000000000000000000011_111```
# ``````0ΒΆΒΆ0ΒΆΒΆΒΆ0ΒΆΒΆ0000000000000000000000000000ΒΆ01`1_11_``
# ``````ΒΆΒΆΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆ0000000000000000000000000000001`_0_11_`
# ``````ΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆΒΆ00000000000000000000000000000ΒΆ01``_0_11`
# ``````ΒΆΒΆΒΆΒΆ0ΒΆΒΆΒΆΒΆ00000000000000000000000000000001```_1_11
| 8 | PYTHON3 |
t = int(input())
def cheatScore(s, n, k):
lose = 0
score = 0
start = 0
tmp = []
flag = 0
Alllose = 1
for c in s:
if c != 'W':
continue
else:
Alllose = 0
break
if Alllose:
return max(0, 2*min(n, k)-1)
for i in range(len(s)):
if i == 0:
if s[i] == 'L':
count = 1
flag = 1
else:
continue
if s[i] == 'L':
if s[i-1] == 'W':
count = 1
elif s[i-1] == 'L':
count += 1
else:
if s[i-1] == 'L':
tmp.append(count)
else:
continue
stEnd = 0
if flag:
stEnd += tmp.pop(0)
if s[-1] == 'L':
stEnd += count
tmp = sorted(tmp)
#print(s, stEnd, tmp)
for i in range(len(s)):
if i == 0:
if s[i] == 'W':
score += 1
else:
lose += 1
continue
if s[i] == 'W':
if s[i-1] == 'W':
score += 2
else:
score += 1
else:
lose += 1
score += 2 * min(lose, k)
bridge = 0
leave = 0
for gap in tmp:
if k >= gap:
bridge += 1
k -= gap
else:
leave += gap
score += bridge
return score
while t:
t -= 1
n, k = list(map(int, input().strip().split()))
s = input()
maxScore = cheatScore(s, n, k)
print(maxScore)
| 8 | PYTHON3 |
for __ in range(int(input())):
n, m = list(map(int, input().split()))
ar = list(input())
kek = []
ans = 0
if 'W' in ar:
i = ar.index('W')
flag = 0
cnt = 0
while i < n:
if ar[i] == 'L' and flag == 0:
flag = 1
cnt = 1
elif ar[i] == 'L':
cnt += 1
elif ar[i] == 'W' and flag == 1:
kek.append(cnt)
flag = 0
i += 1
else:
ans -= 1
kek.sort()
bebe = m
j = 0
while bebe > 0 and j < len(kek):
if bebe - kek[j] >= 0:
ans += kek[j] * 2 + 1
else:
break
bebe -= kek[j]
j += 1
ans += 2 * (bebe - max(0, m - ar.count('L')))
for i in range(n):
if i == 0:
if ar[i] == 'W':
ans += 1
else:
if ar[i] == ar[i - 1] == 'W':
ans += 2
elif ar[i] == 'W':
ans += 1
print(max(ans, 0)) | 8 | PYTHON3 |
t = int(input())
for _ in range(t):
n,k = map(int,input().split())
s = list(input())
w = 0
for x in s:
if x == 'W':
w += 1
if k >= n-w:
print(1 +(n-1)*2)
else:
a = -1
b = -3
for i in range(n):
if s[i] == 'W':
a = i
break
for i in range(n):
if s[n - i - 1] == 'W':
b = n - i - 1
break
prev = False #if prev is win
holes = {}
h = 0
for i in range(a,b+1):
if s[i] == 'W':
if h in holes:
holes[h].append(i-1)
else:
if h > 0:
holes[h] = [i-1]
h = 0
if not prev:
prev = True
else:
h += 1
if prev:
prev = False
nums = {}
sorted_keys_holes = sorted(holes.keys())
for h in sorted_keys_holes:
if h > k:
break
else:
x = min(k // h, len(holes[h]))
nums[h] = []
for r in range(x):
nums[h].append((holes[h][r] - h, holes[h][r]))
k -= x*h
for h in nums.keys():
for r in nums[h]:
i,j = r
for l in range(i,j+1):
s[l] = 'W'
c = 0
prev = False
for i in range(a, b+1):
if s[i] =='W':
if prev:
c += 2
else:
c += 1
prev = True
else:
prev = False
if c > 0:
print(c + 2*k)
else:
if k > 0:
print(1+2*(k-1))
else:
print(0)
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int t, n, K;
char ch[maxn];
int main() {
cin >> t;
while (t--) {
cin >> n >> K >> ch + 1;
ch[0] = 'L';
int q = 0, res = 0;
for (int i = 1; i <= n; i++) {
res += (ch[i] == 'W') + (ch[i] == 'W' && ch[i - 1] == 'W');
}
vector<int> v;
int i = 1;
while (i <= n && ch[i] == 'L') i++;
if (i == n + 1) {
if (K)
cout << 2 * min(K, n) - 1 << "\n";
else
cout << "0\n";
continue;
}
q += i - 1;
for (int j; i <= n; i = j) {
j = i;
while (j <= n && ch[j] == 'W') j++;
int k = j;
while (j <= n && ch[j] == 'L') j++;
if (j <= n)
v.push_back(j - k);
else
q += j - k;
}
sort(v.begin(), v.end());
for (int i = 0; i < v.size() && K; i++) {
if (K >= v[i]) {
res += v[i] * 2 + 1;
K -= v[i];
} else {
res += K * 2;
K = 0;
}
}
if (K) {
res += 2 * min(q, K);
}
cout << res << "\n";
}
}
| 8 | CPP |
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
s=list(input())
ind=[]
ans=0
for i in range(n):
if s[i]=='W':
ind.append(i)
if i-1>=0 and s[i-1]=='W':
ans+=1
ans+=1
if k==0:
print(ans)
elif len(ind)==0:
print(min(k,n)*2-1)
else:
gap=[]
for i in range(len(ind)-1):
gap.append(ind[i+1]-ind[i]-1)
gap.sort()
k=min(k,n-len(ind))
ans+=2*k
for i in gap:
if i>0:
if k>=i:
ans+=1
k-=i
else:
break
print(ans) | 8 | PYTHON3 |
import os
import heapq
import sys, threading
import math
import operator
from collections import defaultdict, deque
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 5)
# threading.stack_size(2**27)
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def pw(a, b, md):
result = 1
while (b > 0):
if (b % 2 == 1):
result *= a
result %= md
a *= a
a %= md
b //= 2
return result % md
def inpt():
return [int(k) for k in input().split()]
def main():
for _ in range(int(input())):
n,k=inpt()
ar=list(input())
start=-1
prev=-1
temp=[]
for i in range(n):
if(ar[i]=='W'):
if(prev==-1):
prev=i
start=i
else:
temp.append((i-prev-1,prev+1,i))
prev=i
temp.sort()
for i in temp:
if(k==0):
break
p,l,r=i
for j in range(l,r):
ar[j]='W'
k-=1
if(k==0):
break
if(k>0):
for i in range(prev+1,n):
ar[i]='W'
k-=1
if(k==0):
break
if(k>0):
for i in range(start-1,-1,-1):
ar[i]='W'
k-=1
if(k==0):
break
ans=0
for i in range(n):
if(ar[i]=='W'):
if(i==0 or ar[i-1]=='L'):
ans+=1
else:
ans+=2
print(ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
# main()
threading.Thread(target=main).start() | 8 | PYTHON3 |
for j in range(int(input())):
n,k=map(int,input().split())
r=input()
a=[]
t=r[0]
s=1
for i in range(1,n):
if r[i]==t:
s+=1
else:
a.append([t,s])
t=r[i]
s=1
a.append([t,s])
b=[]
h=len(a)
s=0
m=0
t=0
if a[0][0]=='L':
s=1
if a[-1][0]=='L':
h-=1
for i in range(s,h):
if a[i][0]=='W':
m+=a[i][1]
t+=1
else:
b.append(a[i][1])
b.sort()
i=0
s=0
while i<len(b) and s+b[i]<=k:
t-=1
s+=b[i]
i+=1
m+=s
if i<len(b) and s<k:
m+=k-s
elif i==len(b) and s<k:
f=0
if a[0][0]=='L':
f+=a[0][1]
if a[-1][0]=='L':
f+=a[-1][1]
if m==0:
t=1
m+=min(k-s,f)
print(2*m-t) | 8 | PYTHON3 |
from collections import deque
def solve():
n, k = map(int, input().split())
data = list(input())
data.append("E")
pointer = 0
que = []
combo = 0
res = 0
which = 0
for i in range(n):
if i == 0:
if data[i] == "W":
which = 1
else:
which = -1
combo = 1
else:
if which < 0:
if data[i] == "W":
if i>combo:
que.append(combo)
combo = 1
which = 1
elif data[i] == "L":
combo += 1
elif which > 0:
if data[i] == "W":
combo += 1
else:
res += 2*combo - 1
combo = 1
which = -1
if combo > 0 and which > 0:
res += 2*combo - 1
que.sort()
que = deque(que)
cheat = k
if res == 0:
print(min(2*n-1,max(2*k-1,0)))
return
while que and que[0] <= cheat:
v = que.popleft()
res += 2*v+1
cheat -= v
res += 2*cheat
ans = min(res, 2*n-1)
print(ans)
return
def main():
t = int(input())
for i in range(t):
solve()
return
if __name__ == "__main__":
main()
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int max_n = 100000;
int n, k;
char s[max_n + 5];
void solve(void);
int main(void) {
int t;
scanf("%d", &t);
while (t--) solve();
return 0;
}
void solve(void) {
scanf("%d%d", &n, &k);
scanf("%s", s);
int i, j, t, ans = 0;
int lcnt = 0;
for (i = 0; i < n; i++) {
if (s[i] == 'W') {
if (i > 0 && s[i - 1] == 'W')
ans += 2;
else
ans++;
} else
lcnt++;
}
if (lcnt == n) {
if (!k)
printf("0\n");
else
printf("%d\n", 2 * k - 1);
return;
}
i = 0;
vector<int> gap;
while (i < n) {
if (s[i] == 'L') {
i++;
continue;
}
j = i;
while (j < n && s[j] == 'W') j++;
t = j;
while (t < n && s[t] == 'L') t++;
if (t >= n) break;
gap.push_back(t - j);
i = t;
}
sort(gap.begin(), gap.end());
for (i = 0; k && i < (int)gap.size(); i++) {
if (gap[i] <= k) {
k -= gap[i];
lcnt -= gap[i];
ans += 2 * gap[i] + 1;
} else {
lcnt -= k;
ans += 2 * k;
k = 0;
}
}
if (k) {
ans += min(k, lcnt) * 2;
}
printf("%d\n", ans);
}
| 8 | CPP |
from sys import stdin,stdout
from collections import *
from math import ceil, floor , log, gcd
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:map(int,stdin.readline().split())
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
mod=1000000007
INF=float('inf')
def solve():
n,k=mp()
s=st()
if s.count('W')==0:
print(max(0,2*k -1))
return
ans=0
W=0
cur=0
w=0
x=[]
for i in range(n):
if s[i]=='W':
if cur:
x.append(cur)
cur=0
ans+=1
w+=1
if W:
ans+=1
W=1
else:
W=0
if w:
cur+=1
k=min(k,n-w)
ans+= 2*k
x.sort()
for i in x:
if i<=k:
ans+=1
k-=i
pr(ans)
for _ in range(inp()):
solve()
| 8 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int cntl = 0;
for (int i = 0; i < n; i++) {
cntl += (s[i] == 'L');
}
if (k >= cntl) {
cout << 2 * n - 1 << "\n";
continue;
}
if (cntl == n) {
cout << max(2 * k - 1, 0) << "\n";
continue;
}
int basic = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') {
basic++;
if (i > 0 && s[i - 1] == 'W') basic++;
}
}
int cnt = -1;
vector<int> segs;
for (int i = 0; i < n; i++) {
if (s[i] == 'W') {
if (cnt > 0) segs.push_back(cnt);
cnt = 0;
} else {
if (cnt != -1) cnt++;
}
}
sort(segs.begin(), segs.end());
for (int l : segs) {
if (k >= l) {
basic += 2 * l + 1;
k -= l;
}
}
basic += 2 * k;
cout << basic << "\n";
}
return 0;
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int go = 0;
vector<pair<char, int>> cnt;
for (auto c : s) {
if (c == 'W') ++go;
if (cnt.empty() || cnt.back().first != c) cnt.push_back({c, 0});
++cnt.back().second;
}
if (go == 0) {
cout << max(0, 2 * k - 1) << '\n';
continue;
}
go += k;
go = min(go, n);
vector<int> have;
for (int i = 1; i + 1 < (int)cnt.size(); ++i) {
if (cnt[i - 1].first == 'W' && cnt[i].first == 'L' &&
cnt[i + 1].first == 'W') {
have.push_back(cnt[i].second);
}
}
sort(have.begin(), have.end());
int cmp = (int)have.size() + 1;
for (auto x : have) {
if (k >= x) {
k -= x;
--cmp;
}
}
cout << 2 * go - cmp << '\n';
}
}
| 8 | CPP |
#include <bits/stdc++.h>
using namespace std;
char st[100003];
int main() {
int t, n, k;
vector<int> vec;
scanf("%d", &t);
while (t--) {
vec.clear();
scanf("%d %d", &n, &k);
scanf("%s", st + 1);
int cnt = 0, i, srt = 0, sum = 0;
for (i = 1; i <= n; i++) {
if (st[i] == 'W' && srt == 0) srt = i;
if (st[i] == 'W') {
sum++;
if (st[i - 1] == 'W') sum++;
}
}
if (k == 0) {
printf("%d\n", sum);
continue;
}
if (srt == 0) {
printf("%d\n", (k - 1) * 2 + 1);
continue;
}
for (i = srt + 1; i <= n; i++) {
if (st[i] == 'W') {
if (cnt) vec.push_back(cnt);
cnt = 0;
} else
cnt++;
}
sort(vec.begin(), vec.end());
for (int v : vec) {
int tar = min(v, k);
sum += tar * 2 + (tar == v);
k -= tar;
}
for (i = 1; k > 0 && i <= n; i++) {
if (st[i] == 'W') break;
k--;
sum += 2;
}
for (i = n; k > 0 && i >= 1; i--) {
if (st[i] == 'W') break;
k--;
sum += 2;
}
printf("%d\n", sum);
}
}
| 8 | CPP |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.