Harryxun/GPT-100-sft-dataset huggingface dataset:
Problem p02697 (python)

Fixed submission:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, m = map(int, input().split())
if n % 2 == 0:
    n -= 1
ans = []
left_range = n//2
right_range = n//2 - 1
left1 = 1
right1 = 1 + left_range
left2 = right1 + 1
right2 = left2 + right_range

while True:
    if left1 >= right1:
        break
    ans.append([left1, right1])
    left1 += 1
    right1 -= 1

while True:
    if left2 >= right2:
        break
    ans.append([left2, right2])
    left2 += 1
    right2 -= 1
    
for i in range(m):
    print(*ans[i])

Buggy submission (verdict: Runtime Error):
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, m = map(int, input().split())
if n % 2 == 0:
    n -= 1
ans = []
left_range = n//2
right_range = n//2 - 1
left1 = 1
right1 = 1 + left_range
left2 = right1 + 1
right2 = left2 + right_range

while True:
    left1 += 1
    right1 -= 1
    if left1 >= right1:
        break
    ans.append([left1, right1])

while True:
    left2 += 1
    right2 -= 1
    if left2 >= right2:
        break
    ans.append([left2, right2])
    
for i in range(m):
    print(*ans[i])

Buggy submission (verdict: Runtime Error):
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, m = map(int, input().split())
if n % 2 == 0:
    n -= 1
ans = []
if m % 2 == 0:
    right_range = n//2
    left_range = n//2 - 1
else:
    left_range = n//2
    right_range = n//2 - 1
left1 = 1
right1 = 1 + left_range
left2 = right1 + 1
right2 = left2 + right_range

for i in range(left_range):
    left1 += i
    right1 -= i
    if left1 >= right1:
        break
    ans.append([left1, right1])

for i in range(right_range):
    left2 += i
    right2 -= i
    if left2 >= right2:
        break
    ans.append([left2, right2])
    
for i in range(m):
    print(*ans[i])

Buggy submission (verdict: Runtime Error):
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, m = map(int, input().split())
ans = []
if m % 2 == 0:
    right_range = n//2
    left_range = n//2 - 1
else:
    left_range = n//2
    right_range = n//2 - 1
left1 = 1
right1 = 1 + left_range
left2 = right1 + 1
right2 = left2 + right_range

for i in range(left_range):
    left1 += i
    right1 -= i
    if left1 >= right1:
        break
    ans.append([left1, right1])

for i in range(right_range):
    left2 += i
    right2 -= i
    if left2 >= right2:
        break
    ans.append([left2, right2])
    
for i in range(m):
    print(*ans[i])

Buggy submission (verdict: Runtime Error):
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, m = map(int, input().split())
ans = []
need = n//2 if n % 2 else (n - 1)//2
left_range = need
right_range = need - 1
left1 = 1
right1 = 1 + left_range
left2 = right1 + 1
right2 = left2 + right_range

for i in range(left_range):
    left1 += i
    right1 -= i
    if left1 >= right1:
        break
    ans.append([left1, right1])

for i in range(right_range):
    left2 += i
    right2 -= i
    if left2 >= right2:
        break
    ans.append([left2, right2])
    
for i in range(m):
    print(*ans[i])
Problem p02716 (python)

Fixed submission:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

def solve():
    n = int(input())
    a = [int(x) for x in input().split()]

    from collections import defaultdict

    dp = defaultdict(lambda : -float('inf'))
    dp[(0, 0, 0)] = 0

    for i in range(1, n + 1):
        max_j = i//2 if i % 2 == 0 else i//2 + 1
        min_j = n//2 - (n - i)//2 if (n - i) % 2 == 0 else n//2 - ((n - i)//2 + 1)
        for j in range(min_j, max_j + 1):
            dp[(i, j, 0)] = max(dp[(i - 1, j, 0)], dp[(i - 1, j, 1)])
            dp[(i, j, 1)] = dp[(i - 1, j - 1, 0)] + a[i - 1]
    print(max(dp[(n, n//2, 0)], dp[(n, n//2, 1)]))
solve()

Buggy submission (verdict: Runtime Error):
#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(ll i = 0; i < (ll)(n); i++)
#define inf 1001001001
#define mod 1000000007
#define mod2 998244353
#define pi acos(-1)
#define all(x) (x).begin(),(x).end()
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  cout << setprecision(15) << fixed;

  ll n; cin >> n;
  vector<ll> a(n);
  rep(i, n) cin >> a[i];

  map<tuple<ll, ll, ll>, ll> dp;
  dp[{0, 0, 0}] = 0;

  for (ll i = 1; i < n + 1; i++) {
    ll maxj = (i % 2 == 0)? i/2 : i/2 + 1;
    ll minj = ((n - 1) % 2 == 0)? n/2 - (n - i)/2 : n/2 - ((n - i)/2 + 1);
    for (ll j = minj; j < maxj + 1; j++) {
      dp[{i, j, 0}] = -inf;
      if (dp.count(make_tuple(i - 1, j, 0))) chmax(dp[{i, j, 0}], dp[{i - 1, j, 0}]);
      if (dp.count(make_tuple(i - 1, j, 1))) chmax(dp[{i, j, 0}], dp[{i - 1, j, 1}]);
      dp[{i, j, 1}] = -inf;
      if (dp.count(make_tuple(i - 1, j - 1, 0))) chmax(dp[{i, j, 1}], dp[{i - 1, j - 1, 0}] + a[i - 1]);
    }
  }
  cout << max(dp[{n, n/2, 0}], dp[{n, n/2, 1}]) << endl;
}
Problem p02742 (python)

Fixed submission:
import sys
input = sys.stdin.readline

H, W = [int(x) for x in input().split()]
ans = 0

if H == 1 and W == 1:
    print(1)
    sys.exit()

if H == 1 or W == 1:
    print(1)
    sys.exit()

# type2
b = H // 2

# type1
a = H - b

ans += b * (W // 2)
ans += a * (W - (W // 2))

print(ans)

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline

H, W = [int(x) for x in input().split()]

d = [[-1] * W for _ in range(H)]
def dfs(x, y):
    stack = [(x, y)]
    d[x][y] = 1
    while stack:
        x, y = stack.pop()
        next_ = [(x + 1, y + 1), (x + 1, y - 1), (x - 1, y + 1), (x - 1, y - 1)]
        for i in next_:
            nx, ny = i
            if 0 <= nx < H and 0 <= ny < W and d[nx][ny] < 0:
                stack.append((nx, ny))
                d[nx][ny] = 1
    return d

d = dfs(0, 0)
cnt = 0
for i in d:
    for j in i:
        if j == 1:
            cnt += 1

print(cnt)
Problem p02743 (python)

Fixed submission:
import sys
input = sys.stdin.readline
import math
a, b, c = [int(x) for x in input().split()]

c -= (a + b)
if c <= 0:
    print("No")
    sys.exit()

c = c ** 2 - 4 * a * b

if c > 0:
    print("Yes")
else:
    print("No")

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readlinH, W = [int(x) for x in input().split()]

a, b, c = [int(x) for x in input().split()]

if a ** (1 / 2) + b ** (1 / 2) < c ** (1 / 2):
    print("Yes")
else:
    print("No")
Problem p02765 (python)

Fixed submission:
import sys
input = sys.stdin.readline

N, R = [int(x) for x in input().split()]

if N >= 10:
    print(R)
else:
    print(R + 100 * (10 - N))

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline

N, R = [int(x) for x in input().split()]

if N >= 10:
    print(R)
else:
    print(R + 100 * (10 - K))
Problem p02796 (python)

Fixed submission:
import sys
input = sys.stdin.readline

N = int(input())
XL = []
for _ in range(N):
    tmp = [int(x) for x in input().split()]
    XL.append(tmp)
LR = []
for i in XL:
    LR.append([i[0] - i[1], i[0] + i[1]])
LR.sort()
ans = N
last = LR[0][1]
for i in range(1, N):
    if last > LR[i][0]:
        if last > LR[i][1]:
            last = LR[i][1]
        ans -= 1
    else:
        last = LR[i][1]
print(ans)

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline
N = int(input())
XL = []
import numpy as np
for _ in range(N):
    XL.append([int(x) for x in input().split()])
XL = np.array(sorted(XL))
XL_max = []
XL_min = []
for i in XL:
    XL_max.append(i[0] + i[1])
    XL_min.append(i[0] - i[1])
A = [0] * N
for i in range(N):
    cnt = 0
    left = sorted(XL_max[:i])
    right = sorted(XL_min[i+1:])
    cnt += i - np.searchsorted(left, XL_min[i], side = "right") 
    cnt += np.searchsorted(right, XL_max[i], side = "left")
    A[i] = cnt
cnt = np.array(sorted(A, reverse=True), np.int64)
cnt = np.cumsum(cnt)
if cnt[-1] == 0:
    print(n)
else:
    print(N - (np.searchsorted(cnt, cnt[-1] // 2) + 1))

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline
N = int(input())
X = []
L = []
XL = []
for _ in range(N):
    XL.append([int(x) for x in input().split()])
XL = sorted(XL)
for i in XL:
    X.append(i[0])
    L.append(i[1])
import numpy as np
X = np.array(X, np.int64)
L = np.array(L, np.int64)
XL_max = X + L
XL_min = X - L
A = [0] * N
for i in range(N):
    cnt = 0
    left = sorted(XL_max[:i])
    right = sorted(XL_min[i+1:])
    cnt += i - np.searchsorted(left, XL_min[i], side = "right") 
    cnt += np.searchsorted(right, XL_max[i], side = "left")
    A[i] = cnt
cnt = np.array(sorted(A, reverse=True), np.int64)
cnt = np.cumsum(cnt)
if cnt[-1] == 0:
    print(n)
else:
    print(N - (np.searchsorted(cnt, cnt[-1] // 2) + 1))
Problem p02801 (python)

Fixed submission:
import sys
input = sys.stdin.readline
C = input().rstrip()
al = [chr(i) for i in range(97, 97+26)]
alpha2num = lambda c: ord(c) - ord("a")
print(al[alpha2num(C) + 1])

Buggy submission (verdict: Runtime Error):
def cmb(n, k, mod, fac, ifac):
    """
    nCkを計算する
    """
    k = min(k, n-k)
    return fac[n] * ifac[k] * ifac[n-k] % mod


def make_tables(mod, n):
    """
    階乗テーブル、逆元の階乗テーブルを作成する
    """
    fac = [1, 1] # 階乗テーブル・・・(1)
    ifac = [1, 1] #逆元の階乗テーブル・・・(2)
    inverse = [0, 1] #逆元テーブル・・・(3)

    for i in range(2, n+1):
        fac.append((fac[-1] * i) % mod)
        inverse.append((-inverse[mod % i] * (mod//i)) % mod)
        ifac.append((ifac[-1] * inverse[-1]) % mod)
    return fac, ifac
    
n,k=map(int,input().split())
a=sorted(list(map(int, input().split())))
MOD=10**9+7

fac, ifac=make_tables(MOD,n)

s=0
for i in range(k-1,n):
	s+=(a[i]-a[n-i-1])*cmb(i,k-1,MOD,fac,ifac)
	s%=10**9+7
print(s)
Problem p02814 (python)

Fixed submission:
import sys
input = sys.stdin.readline
import numpy as np
N, M = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a_num = np.array(a)
x = a_num // 2
count_even = np.count_nonzero(x % 2 == 0)
if count_even != 0 and count_even != N:
    print(0)
    sys.exit()
c = []
from collections import Counter
if count_even == N:
    for i in x:
        cnt = 0
        cnt = format(i, 'b')[::-1].find('1')
        c.append(cnt)
    c = Counter(c)
    if len(c.keys()) != 1:
        print(0)
        sys.exit()
    
import fractions
from functools import reduce
def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)
def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)

minmulti = lcm(* x)
temp = M // minmulti
if temp % 2 == 0:
    print(temp // 2)
else:
    print(1 + temp // 2)

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline
import numpy as np
N, M = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a_num = np.array(a)
x = a_num // 2
count_even = np.count_nonzero(x % 2 == 0)
if count_even != 0 and count_even != N:
    print(0)
    sys.exit()
c = []
from collections import Counter
if count_even == N:
    for i in x:
        cnt = 0
        while i % 2 == 0:
            cnt += 1
            i //= 2
        c.append(ans)
    c = Counter(c)
    if len(c.keys()) != 1:
        print(0)
        sys.exit()
    
import fractions
from functools import reduce
def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)
def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)

minmulti = lcm(* x)
temp = M // minmulti
if temp % 2 == 0:
    print(temp // 2)
else:
    print(1 + temp // 2)
Problem p02824 (python)

Fixed submission:
import sys
input = sys.stdin.readline

n, m, v, p = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a.sort()
a = a[::-1]

ans = p

b = a[p:]
b_cumsum = [a[p - 1]]
for i in b:
    b_cumsum.append(b_cumsum[-1] + i)

for i in range(len(b)):
    vote_cnt = max(0, (v - p - (len(b) - (i + 1))))
    if b_cumsum[i] + m * vote_cnt <= (b[i] + m) * (i + 1) and a[p - 1] <= b[i] + m:
        ans += 1
    else:
        break

print(ans)

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline
N, M, V, P = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
A = sorted(A)
kakutei = A[-P]
kakutei_idx = A.index(kakutei)
ans = N - kakutei_idx
V -= (ans - 1)
A = A[:kakutei_idx]
A = sorted(A, reverse=True)
N = len(A)
kakutei_muri = A[-(V - 1)]
kakutei_muri_idx = A.index(kakutei_muri)
ans += (kakutei_muri_idx)
print(ans)
Problem p02837 (python)

Fixed submission:
import sys
input = sys.stdin.readline
import numpy as np
N = int(input())
S = [[] for _ in range(N)]
for i in range(N):
    A = int(input())
    temp = []
    for _ in range(A):
        temp.append([str(x) for x in input().split()])
        S[i] = temp
ans = 0
for i in range(2 ** N - 1, -1,-1):
    biti = list(bin(i)[2:].zfill(N))
    flag = 0
    for j in range(N):
        if biti[j] == "1":
            for k in S[j]:
                if biti[int(k[0])-1] != k[1]:
                    flag = 1
                    break
        if flag:
            break
    if not flag:    
        biti = np.array(biti)
        ans = max(ans, np.count_nonzero(biti == "1"))
print(ans)

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline

n = int(input())

from collections import defaultdict
d = defaultdict(list)

for i in range(n):
    a = int(input())
    for _ in range(a):
        x, y = [int(x) for x in input().split()]
        d[i].append((x - 1, y))
ans = 0
for k in range(2**n):
    res = 0
    j = bin(k)[2:].zfill(n)
    for i in range(n):
        if j[i] == "0":
            continue
        flag = 1
        for x, y in d[i]:
            if int(j[x]) != int(y):
                flag = 0
                break
        res += 1
    if flag:
        ans = max(ans, res)
print(ans)
Problem p02853 (python)

Fixed submission:
import sys
input = sys.stdin.readline

x, y = [int(x) for x in input().split()]
ans = 0

for i in [x, y]:
    if i == 1:
        ans += 300000
    elif i == 2:
        ans += 200000
    elif i == 3:
        ans += 100000
    
if x == 1 and y == 1:
    ans += 400000

print(ans)

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline

n = int(input())
a = [int(x) for x in input().split()]

mean = sum(a) / n

ans = [200, 200]

for i in range(n):
    if abs(mean - a[i]) < ans[1]:
        ans = [i, abs(mean - a[i])]

print(ans[0])
Problem p02855 (python)

Fixed submission:
from collections import deque
H,W,K = list(map(int, input().split()))
A = [[0] * W for _ in range(H)]
n = 1
P = []
B = []
for i in range(H):
    B.append(input())

for i in range(H):
    for j in range(W):
        if B[i][j] == "#":
            A[i][j] = n
            n += 1
            P.append([i,j])
def change(A,x,y,z):
    if y-1 >= 0:
        if A[x][y-1] == 0:
            A[x][y-1] = z
            change(A,x,y-1,z)
    if y + 1 <= (W-1):
        if A[x][y+1] == 0:
            A[x][y+1] = z
            change(A,x,y+1,z)
for i in P:
    change(A,i[0],i[1],A[i[0]][i[1]])
next_ = []
next_ = deque(next_)
for k in range(H):
    if 0 in A[k]:
        next_.append(k)
while len(next_) > 0:
    l = next_.popleft()
    if l == H-1:
        A[l] = A[l-1]
        if 0 in A[l]:
            next_.append(l)
    elif l == 0:
        A[l] = A[l+1]
        if 0 in A[l]:
            next_.append(l)
    else:
        if l+1 in next_ and l - 1 in next_:
            next_.append(l)
        elif l + 1 not in next_:
            A[l] = A[l + 1]
        else:
            A[l] = A[l - 1]
for w in range(H):
    print(*A[w])

Buggy submission (verdict: Runtime Error):
from collections import deque
H,W,K = list(map(int, input().split()))
A = [[0] * W for _ in range(H)]
n = 1
P = []
B = []
for i in range(H):
    B.append(input())

for i in range(H):
    for j in range(W):
        if B[i][j] == "#":
            A[i][j] = n
            n += 1
            P.append([i,j])
def change(A,x,y,z):
    if y-1 >= 0:
        if A[x][y-1] == 0:
            A[x][y-1] = z
            change(A,x,y-1,z)
    if y + 1 <= (W-1):
        if A[x][y+1] == 0:
            A[x][y+1] = z
            change(A,x,y+1,z)
for i in P:
    change(A,i[0],i[1],A[i[0]][i[1]])
next_ = []
next_ = deque(next_)
for k in range(H):
    if 0 in A[k]:
        next_.append(k)
while len(next_) > 0:
    l = next_.popleft()
    if l == H-1:
        A[l] = A[l-1]
        if 0 in A[l]:
            next_.append(next_.popleft())
    else:
        A[l] = A[l+1]
        if 0 in A[l]:
            next_.append(next_.popleft())
for w in range(H):
    print(*A[w])

Buggy submission (verdict: Runtime Error):
from collections import deque
H,W,K = list(map(int, input().split()))
A = [[0] * W for _ in range(H)]
n = 1
P = []
B = []
for i in range(H):
    B.append(input())

for i in range(H):
    for j in range(W):
        if B[i][j] == "#":
            A[i][j] = n
            n += 1
            P.append([i,j])
def change(A,x,y,z):
    if y-1 >= 0:
        if A[x][y-1] == 0:
            A[x][y-1] = z
            change(A,x,y-1,z)
    if y + 1 <= (W-1):
        if A[x][y+1] == 0:
            A[x][y+1] = z
            change(A,x,y+1,z)
for i in P:
    change(A,i[0],i[1],A[i[0]][i[1]])
next_ = []
next_ = deque(next_)
for k in range(H):
    if 0 in A[k]:
        next_.append(k)
while len(next_) > 0:
    l = next_.popleft()
    if l == H-1:
        A[l] = A[l-1]
        if 0 in A[l]:
            next_.append(next_.popleft())
    else:
        A[l] = A[l+1]
        if 0 in A[l]:
            next_.append(next_.popleft())
for w in range(H):
    print(*A[w])
Problem p02883 (python)

Fixed submission:
import numpy as np
N,K = map(int,input().split())
A = np.array(list(map(int,input().split())))
F = np.array(list(map(int,input().split())))
A = np.sort(A)
F = np.sort(F)[::-1]
Asum = A.sum()

def test(x):
    return Asum - np.minimum(A,x//F).sum() <= K

left = -1
right = np.amax(A * F)

while right - left > 1:
    mid = (right + left)//2
    if test(mid) == 1:
        right = mid
    else:
        left = mid
print(right)

Buggy submission (verdict: Runtime Error):
import numpy as np
N,K = map(int,input().split())
A = np.array(list(map(int,input().split())))
F = np.array(list(map(int,input().split())))
A = np.sort(A)
F = np.sort(F)[::-1]
Asum = A.sum()

def test(x):
    return Asum - np.minimum(A,x//F).sum() <= K

left = -1
right = np.amax(A * F)

while right - left > 1:
    mid = (right + left)//2
    if test(mid) == 1:
        right = mid
    else:
        left = mid
print(right)

Buggy submission (verdict: Runtime Error):
def main():
    N,K=map(int,input().split())
    A=list(map(int,input().split()))
    F=list(map(int,input().split()))
    A.sort()
    F.sort(reverse=True)
    i = 0
    while K > 0:
        if A[0]*F[0] >= A[-1] * F[-1]:
            if K > A[0]:
                K -= A.pop(0)
            else:
                A[0] -= K
                K = 0
                break
        else:
            if K >= A[-1]:
                K -= A.pop(-1)
                F.pop(-1)
            else:
                A[-1] -= K
                K=0
                break
        
    S = 0
    for j in range(len(A)):
        S += A[j] * F[j]
    print(S)
    
if __name__ == '__main__':
    main()
Problem p02900 (python)

Fixed submission:
def main():
    A,B = map(int,input().split())
    import fractions
    C = fractions.gcd(A,B)
    cnt = 0
    def make_divisors(n):
        divisors = []
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.append(i)
                if i != n // i:
                    divisors.append(n//i)
        return divisors
    def is_prime(n):
        if n == 1:
            return True
        for i in range(2,int(n**0.5)+1):
            if n % i == 0:
                return False
        return True
    
    C_2 = make_divisors(C)
    
    for i in C_2:
        if is_prime(i):
            cnt += 1
    print(cnt)
    
    


    
if __name__ == '__main__':
    main()

Buggy submission (verdict: Runtime Error):
def main():
    A,B = map(int,input().split())
    import math
    C = math.gcd(A,B)
    cnt = 0
    def make_divisors(n):
        divisors = []
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.append(i)
                if i != n // i:
                    divisors.append(n//i)
        return divisors
    def is_prime(n):
        if n == 1:
            return True
        for i in range(2,int(n**0.5)+1):
            if n % i == 0:
                return False
        return True
    
    C_2 = make_divisors(C)
    
    for i in C_2:
        if is_prime(i):
            cnt += 1
    print(cnt)
    
    


    
if __name__ == '__main__':
    main()
Problem p02910 (python)

Fixed submission:
S=input()
N = len(S)
S_o=[]
S_e=[]
for i in range(N):
    if i%2==0:
        S_o.append(S[i])
    else:
        S_e.append(S[i])
if 'L' in S_o or 'R' in S_e:
    print('No')
else:
    print('Yes')

Buggy submission (verdict: Runtime Error):
S=input()
N = len(S)
ans=0
for i in range(N+1):
    if i%2==0:
        if S[i]=='L':
            print('No')
        else:
            ans+=1
    else:
        if S[i]=='R':
            print('No')
        else:
            ans+=1
if ans==2:
    print('Yes')
Problem p02918 (python)

Fixed submission:
from collections import deque
N,K = list(map(int,input().split()))
S = list(input())
S = deque(S)
ans = 0
S_2 = [S.popleft()]
while len(S) > 0:
    if S[0] == S_2[-1]:
        ans += 1
        S.popleft()
    else:
        S_2.append(S.popleft())
cnt = 0

for i in range(1,len(S_2)-1):
    if S_2[i] != S_2[i-1] and S_2[i] != S_2[i+1]:
        ans += 2
        K -= 1
        S_2[i] = S_2[i-1]
        if K ==0:
            break
if len(S_2) == 1:
    print(ans) 
elif len(S_2) == 2:
    if S_2[0] == S_2[1] or K == 0:
        print(ans)
    else:
        print(ans + 1)
else:
    if S_2[0] != S_2[1] and S_2[-1] != S_2[-2] and K > 1:
        print(ans + 2)
    elif K == 0 or (S_2[0] == S_2[1] and S_2[-1] == S_2[-2]):
        print(ans)
    else:
        print(ans + 1)

Buggy submission (verdict: Runtime Error):
from collections import deque
N,K = list(map(int,input().split()))
S = list(input())
S = deque(S)
i = 0
ans = 0
S_2 = [S.popleft()]
while len(S) > 0:
    if S[0] == S_2[-1]:
        ans += 1
        S.popleft()
    else:
        S_2.append(S.popleft())
cnt = 0

for i in range(1,len(S_2)-1):
    if S_2[i] != S_2[i-1] and S_2[i] != S_2[i+1]:
        ans += 2
        K -= 1
        S_2[i] = S_2[i-1]
        if K ==0:
            break
if K > 0:
    if len(S_2) == 1:
        print(ans)
    elif len(S_2) == 2 and S_2[0] != S_2[1]:
        print(ans + 1)
    else:
        if (S[0] != S[1] or S[-1] != S[-2]) and K == 1:
            print(ans + 1)
        elif K > 1 and (S[0] != S[1] and S[-1] != S[-2]):
            print(ans + 2)
        elif K > 1 and (S[0] != S[1] and S[-1] == S[-2]) or (S[0] == S[1] or S[-1] != S[-2]):
            print(ans + 1)
        else:
            print(ans)
else:
    print(ans)