 Connection and Disconnection (AtCoder Grand Contest 039_A)

I am trying to solve this task. Source

A string S is given. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: Choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: Any two adjacent characters in T are different.

Input is given from Standard Input in the following format:

S
K

Print the minimum number of operations required.

Below is the code that I’ve written.
I’ve separated the problem into 5 cases.

i) S is a single letter.

ii) S is two letters and they are the same.

iii) S is two letters and they are different.

iv) S is more than two letters and the first and last letters are different.

v) S is more than two letters and the first and last letters are the same.

S = input()
K = int(input())
L = len(S)
sum = 0
x = 1

if L == 1: # i)
print(K//2)
elif L == 2 and S == S: # ii)
print(K)
elif L == 2: # iii)
print(0)
elif S != S[-1]: # iv)
for i in range(0, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)*K
x = 1
sum += (x // 2)*K
print(sum)
else: # v)
for i in range(0, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)
break
y = x
x = 1
for i in range(y, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)*K
x = 1
sum += (x // 2)
sum += ((x+y) // 2) * (K-1)
print(sum)

My code fails 2 out of 15 test cases. I have no idea what part of my work is causing the issue. Can somebody point out which part of the code is problematic? Thank you!