Problem:


Score : 300 points

Problem Statement

Given is a string S. 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.

Constraints

1 \leq |S| \leq 100

S consists of lowercase English letters.

1 \leq K \leq 10^9

K is an integer.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the minimum number of operations required.

Sample Input 1

issii
2

Sample Output 1

4

T is issiiissii.  For example, we can rewrite it into ispiqisyhi, and now any two adjacent characters are different.

Sample Input 2

qq
81

Sample Output 2

81

Sample Input 3

cooooooooonteeeeeeeeeest
999993333

Sample Output 3

8999939997



Sample input:
issii
2


Sample output:
4

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys
import random
import itertools
import math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt


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


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


def LI_(): return list(map(lambda x: int(x)-1, input().split()))


def II(): return int(input())


def IF(): return float(input())


def LS(): return list(map(list, input().split()))


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


def IR(n): return [II() for _ in range(n)]


def LIR(n): return [LI() for _ in range(n)]


def FR(n): return [IF() for _ in range(n)]


def LFR(n): return [LI() for _ in range(n)]


def LIR_(n): return [LI_() for _ in range(n)]


def SR(n): return [S() for _ in range(n)]


def LSR(n): return [LS() for _ in range(n)]


def gcd(x, y):
    if y == 0:
        return x
    return gcd(y, x % y)


def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]


mod = 1000000007
inf = float('INF')


def A():
    S = input()

    K = II()

    if len(S) == 2:
        print(K//2)
        return

    i = 0
    ans = 0
    A = 1
    p = 0
    z = 0
    z2 = 0
    while(A > 0):
        count = 0
        if i == 0:
            p = 1
        while(S[i] == S[i+1]):

            if S[i+2] == '\n':
                p = 2
            count += 1
            i += 1
        if S[i+1] == '\n':
            p = 2
        if p == 1:
            z = count+1
        if p == 2:
            z2 = count+1

        if(S[i] != S[i+1]):
            i += 1
        if count == len(S)-2:
            print(((len(S)-1)*K)//2)
            return

        if count > 0:
            ans += (count+1)//2

        if S[-1] == S[i]:
            A = -1
        p = 0

    if K >= 2 and S[-2] == S[0] and (z % 2 == 1 and z2 % 2 == 1):
        ans += 1
        print((ans*K)-1)
    else:
        print(ans*K)

    return

# B


def B():
    N, K = map(int, input().split())
    h = LI()
    count = 0

    for i in h:
        if i >= K:
            count += 1
        else:
            continue
    print(count)
    return

# C


def C():
    N = II()
    A = LI()
    J = [0] * N
    for i, n in enumerate(A):
        J[n-1] = i+1
    for s in J:
        print(s, end=" ")

    return

# D


def D():
    A, B = map(int, input().split())
    g = gcd(A, B)
    # go = g
    # myset = set([1])
    sq = int(sqrt(g)) + 2
    ans = 1

    for i in range(2, sq):
        if g % i == 0:
            ans += 1
        while g % i == 0:
            g /= i

            # myset.add(i)
        if g == 1:
            break
        if i == sq - 1:
            # myset.add(go)
            ans += 1

    print(ans)

    return

# E


def E():
    N, M = LI()
    bit_max = 1 << N
    dp = [[inf for i in range(bit_max)] for j in range(M+1)]
    dp[0][0] = 0

    for i in range(M):
        a, b = LI()

        c = LI()
        bit = 0

        for d in c:
            bit |= 1 << (d-1)

        for w in range(bit_max):

            t = w | bit
            cost = dp[i][w] + a

            dp[i+1][t] = min(dp[i+1][t], cost)

            dp[i+1][w] = min(dp[i][w], dp[i+1][w])

    print(-1) if dp[-1][-1] == inf else print(dp[-1][-1])

    return

# F


def F():
    N, M = LI()

    value = [0] * M
    power = [0] * M
    for i in range(M):
        a, b = LI()
        value[i] = a
        c = LI()
        L = ['0'] * N
        for k in c:
            L[k - 1] = '1'
        bint = ''.join(L)
        power[i] = int(bint, 2)
    bint = ''.join(list(['1'] * N))
    dp = [inf] * (int(bint, 2)+1)
    t = 0
    cost = 0

    dp[0] = 0
    for s in range(int(bint, 2) + 1):
        for i in range(M):
            t = s | power[i]
            cost = dp[s] + value[i]
            dp[t] = min(dp[t], cost)
    print(-1) if(dp[-1] == inf) else print(dp[-1])

    return

    # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")


def solution(S):
    # write your code in Python 3.6
    import math

    vowels = "AIUEO"
    count = 0
    consonants = 0
    newC = []
    newV = []

    for i in S[:-1]:
        if i in vowels:
            count += 1
            newV.append(i)
        else:
            consonants += 1
            newC.append(i)

    if consonants < count or consonants - 2 > count:
        return 0

    a = math.factorial(len(set(newC))) * math.factorial(len(set(newV)))
    return a

    pass


# Solve
if __name__ == '__main__':
    A()

Submission status: Accepted

Solution code:
S = input()
K = int(input())
cnt = 0
head = 0
for s in S:
  if s != S[0]:
    break
  head += 1
tail = 0
for s in S[::-1]:
  if s != S[-1]:
    break
  tail += 1
same = 0
for i in range(head, len(S) - tail):
  if S[i] != S[i + 1]:
    cnt += -(-same // 2)
    same = 0
    continue
  same += 1
cnt *= K
if head == len(S):
  cnt = len(S) * K // 2
elif S[0] == S[-1]:
  cnt += head // 2 + (head + tail) // 2 * (K - 1) + tail // 2
else:
  cnt += (head // 2 + tail // 2) * K
print(cnt)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
m=0
j=0
if len(set(list(s)))==1:print((len(s)*k)//2);exit()
for i in range(len(s)):
 if len(s)<=j+1:
  if s[-1]==s[len(s)//3]:print(m*k+k-1)
  else:print(m*k)
  break
 if s[j]==s[j+1]:m+=1;j+=1
 j+=1

Submission status: Accepted

Solution code:
from itertools import groupby

S = input()
K = int(input())

A = [len(tuple(v)) for _, v in groupby(S)]
if len(A) == 1:
    print((A[0] * K) // 2)
    quit()

if S[0] == S[-1]:
    m = sum(a // 2 for a in A) - A[0] // 2 - A[-1] // 2
    print(K * m + (K - 1) * ((A[0] + A[-1]) // 2) + A[0] // 2 + A[-1] // 2)
else:
    print(sum(a // 2 for a in A) * K)

Submission status: Accepted

Solution code:
from itertools import groupby
S = input()
K = int(input())
a = [len(tuple(s)) for _, s in groupby(S)]
ans = 0
 
if S[0] == S[-1] and K > 1:
    if len(a) == 1:
        ans = a[0]*K // 2
    else:
        ans = a[0] // 2 + a[-1] // 2 + (a[0]+a[-1]) // 2 * (K-1)
        ans += sum(n // 2 for n in a[1:-1]) * K
else:
    ans = sum(n // 2 for n in a) * K
print(ans)

Submission status: Accepted

Solution code:
from itertools import groupby

S = input()
K = int(input())

A = [len(tuple(v)) for _, v in groupby(S)]
if len(A) == 1:
    print((len(S) * K) // 2)
    quit()

t = sum(a // 2 for a in A)
if S[0] == S[-1]:
    l, r = A[0], A[-1]
    m = t - l // 2 - r // 2
    print(K * m + (K - 1) * ((r + l) // 2) + r // 2 + l // 2)
else:
    print(t * K)

Submission status: Accepted

Solution code:
S = input()
K = int(input())

ccc = 0
for i in range(len(S)):
    if S[i]==S[0]:
        ccc+=1

if ccc==len(S):
    print(len(S)*K//2)
    exit()

groups = []
char = ''
i=0
j=0
while i<len(S) and j<len(S)-1:
    j+=1
    if S[i]==S[j]:
        char = S[i]
    else:
        if j==i+1:
            i=j
            continue
        groups.append((i,j-1))
        char=''
        i = j
if j!=i:
    groups.append((i,j))



if i==j and i==0:
    print(K//2)
    exit()

ans = 0
temp = 0
temp2 = []
for j in range(len(groups)):
    first = groups[j][0]
    end = groups[j][1]
    if first==0 or end==len(S)-1:
        temp += end-first+1
        temp2.append((first,end))
    else:
        ans += (end-first+1)//2*K

if S[0]==S[-1]:
    for j in range(len(temp2)):
        first = temp2[j][0]
        end = temp2[j][1]
        ans += (end-first+1)//2

    ans += temp//2*(K-1)
else:
    for j in range(len(temp2)):
        first = temp2[j][0]
        end = temp2[j][1]
        ans += (end-first+1)//2*K
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
S = list(input())
N = len(S)
K = int(input())
T = S.copy()
S += S
ans = 0
cnt = 0
f = defaultdict(int)
for t in T:
    f[t] += 1
if len(f) == 1:
    print(N * K // 2)
    exit()
for i in range(1, N):
    if S[i - 1] == S[i]:
        cnt += 1
        S[i] = "-1"
ans += cnt
if T[0] == T[-1] and S[N - 1] != "-1":
    cnt2 = 1
    T[0] = "-1"
    for i in range(1, N):
        if T[i] == T[i - 1]:
            cnt2 += 1
            T[i] = "-1"
    ans += cnt2 * (K - 1)
else:
    ans += cnt * (K - 1)
print(ans)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
chain_hajime=0
chain_owa=0
for i in range(len(s)):
    if s[0]==s[i]:
        chain_hajime+=1
    else: break
for i in range(len(s)):
    if s[-1]==s[-(i+1)]:
        chain_owa+=1
    else: break
#print(chain_hajime)
#print(chain_owa)
import re
def nchars(s, n):
    """文字列 s に、同じ文字が n 個以上連続している部分文字列を見つける
    """

    assert n > 0
    reg = re.compile("(.)\\1{%d,}" % (n - 1))  # カンマを取ると n 個ちょうどになる
    while True:
        m = reg.search(s)
        if not m:
            break
        yield m.group(0)
        s = s[m.end():]
a=list(nchars(s, 2))
b=0
for i in a:
    b+=len(i)//2


if len(set(s))==1:
    print(len(s)*k//2)
elif s[0]!=s[-1]:
    print(b*k)
else:
    print(b*k-(chain_hajime//2+chain_owa//2-(chain_hajime+chain_owa)//2)*(k-1))

Submission status: Accepted

Solution code:
S = list(input())
N = len(S)
K = int(input())
T = S.copy()
S += T
ans = 0
cnt = 0

if N == 1:
    print(K//2)
    exit()

from collections import defaultdict

f = defaultdict(int)
for t in T:
    f[t]+=1
if len(f) == 1:
    print(N*K//2)
    exit()

for i in range(1, N):
    if S[i - 1] == S[i]:
        cnt += 1
        S[i] = "-1"
ans += cnt
if T[0] == T[-1] and S[N - 1] != "-1":
    cnt2 = 0
    for i in range(N):
        if T[i] == T[i - 1]:
            cnt2 += 1
            T[i] = "-1"
    ans += cnt2 * (K - 1)
else:
    ans += cnt * (K - 1)
print(ans)

Submission status: Accepted

Solution code:
from itertools import groupby

S = input()
K = int(input())

A = [len(tuple(v)) for _, v in groupby(S)]
if len(A) == 1:
    print((len(S) * K) // 2)
    quit()

t = sum(a // 2 for a in A)
if S[0] == S[-1]:
    l, r = A[0], A[-1]
    m = l // 2 + r // 2 - (l + r) // 2
    print(t * K - m * (K - 1))
else:
    print(t * K)

Submission status: Accepted

Solution code:
# coding: utf-8


def solve(*args: str) -> str:
    s = args[0]
    k = int(args[1])

    if all([s[0] == c for c in s]):
        return str(int(len(s) * k / 2))

    H = s[0]

    ret = 0
    h = 1
    t = 0
    while H == s[h] and h < len(s):
        h += 1

    while H == s[-t-1] and t < len(s):
        t += 1

    ret += int((h + t) / 2) * (k - 1) + int(h/2) + int(t/2)

    m = 1
    for i in range(h, len(s) - t - 1):
        if s[i] == s[i+1]:
            m += 1
        else:
            ret += int(m/2) * k
            m = 1

    if 1 < m:
        ret += int(m/2) * k

    return str(ret)


if __name__ == "__main__":
    print(solve(*[input() for _ in range(2)]))

Submission status: Accepted

Solution code:
from itertools import groupby

s = input()
k = int(input())
a = [sum(1 for _ in g) for _, g in groupby(s)]
if len(a) == 1:
  print(len(s) * k // 2)
else:
  ans = sum(x // 2 for x in a) * k
  if s[0] == s[-1] and a[0] & a[-1] & 1:
    ans += k - 1
  print(ans)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
m=0
j=0
if len(set(list(s)))==1:print((len(s)*k)//2);exit()
for i in range(len(s)):
 if len(s)<=j+1:
  a=m*k
  if s[0]==s[-1]==s[len(s)//3]:print(a+k-1)
  else:print(a)
  break
 if s[j]==s[j+1]:m+=1;j+=1
 j+=1

Submission status: Accepted

Solution code:
s=input()
k=int(input())
m=0
j=0
if len(set(list(s)))==1:print((len(s)*k)//2);exit()
for i in range(len(s)):
 if len(s)<=j+1:
  a=m*k
  if s[0]==s[-1]==s[len(s)//3]:print(a+k-1)
  else:print(a)
  break
 if s[j]==s[j+1]:
  m+=1
  j+=1
 j+=1

Submission status: Accepted

Solution code:
import sys
s = input()
k = int(input())
w = s * 2

s = list(s)
w = list(w)

same = 0
for i in s:
    if i == s[0]:
        same += 1
if same == len(s):
    ans_s = (len(s)*k) // 2
    print(ans_s)
    sys.exit()

ans_s = 0
ans_w = 0
ans_t = 0
for i in range(0, len(s)-1):
    if s[i] == s[i+1]:
        ans_s += 1
        s[i+1] = "0"

for i in range(0, len(w)-1):
    if w[i] == w[i+1]:
        ans_w += 1
        w[i+1] = "0"

if len(s) == 1:
    ans_s = k // 2
elif (ans_s*2) == ans_w:
    ans_s *= k
else:
    ans_s = ans_s*k + k - 1

print(ans_s)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
if len(set(list(s)))==1:print((len(s)*k)//2);exit()
t=[1]
for i in range(1,len(s)):
  if s[i-1]==s[i]:t[-1]+=1
  else:t.append(1)
a=0
for i in t:a+=(i//2)*k
if s[0]==s[-1]:
  if t[0]%2==t[-1]%2==1:a+=k-1
print(a)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
m=0
j=0
if len(set(list(s)))==1:print((len(s)*k)//2);exit()
for i in range(len(s)):
 if len(s)<=j+1:
  a=m*k
  if s[0]==s[-1]==s[1]==s[len(s)//3]:print(a+k-1)
  else:print(a)
  break;
 if s[j]==s[j+1]:
  m+=1
  j+=1
 j+=1

Submission status: Accepted

Solution code:
S=input()
K=int(input())
LS=len(S)

if LS==1:
    if K==1:
        print(0)
        exit()
    else:
        print(K//2)
        exit()

cnt=1
ans1=0
c=[]
for i in range(1,LS-1):
    if S[i-1]==S[i]:
        cnt+=1
    elif cnt!=1:
        ans1+=cnt//2
        c.append(cnt)
        cnt=1

if K==1:
    if S[-2]==S[-1]:
        cnt+=1
        ans1+=cnt//2
        print(ans1)
        exit()

if S[-2] == S[-1]:
    cnt += 1
    c.append(cnt)
    if cnt % 2 == 0:
        if ans1 != 0:
            ans1 += cnt // 2
            ans1 = ans1 * K
        else:
            ans1 = (cnt // 2) * K
    elif cnt % 2 == 1 and S[0] == S[-1]:
        if ans1 != 0:
            if c[0] % 2 == 0:
                ans1 += cnt // 2
                ans1 = ans1 * K
            else:
                ans1 += cnt // 2 + 1
                ans1 = ans1 * K - 1
        else:
            if ans1!=0:
                ans1 = (cnt // 2) * K + K - 1
            else:
                ans1=(cnt*K)//2
    elif cnt % 2 == 1 and S[0] != S[-1]:
        ans1 += cnt // 2
        ans1 = ans1 * K
else:
    ans1 += cnt // 2

    if S[0] == S[-1]:
        if ans1!=0 and c[0]%2==0:
            ans1=ans1*K
        else:
            ans1 = ans1*K+K - 1
    else:
        ans1 = ans1 * K


print(ans1)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
m=0
j=0
if len(set(list(s)))==1:print((len(s)*k)//2);exit()
for i in range(len(s)):
  if len(s)<=j+1:
    a=m*k
    if s[0]==s[-1]==s[1]==s[len(s)//3]:print(a+k-1)
    else:print(a)
    break;
  if s[j]==s[j+1]:
    m+=1
    j+=1
  j+=1

Submission status: Accepted

Solution code:
def count_changes(s, k, prev=None):
    count = 0
    for _ in range(k):
        for cur in s:
            if cur == prev:
                count += 1
                prev = None
            else:
                prev = cur
    return count, prev


if __name__ == '__main__':
    s = input()
    k = int(input())
    if len(set(s)) == 1:
      print((len(s) * k) // 2)
      exit()
    if k <= 10 ** 8:
        print(count_changes(s, k)[0])
    else:
        base_count, prev = count_changes(s, 3)
        d, rest = divmod(k, 3)
        res = base_count * d
        if rest:
            res += count_changes(s, rest, prev)[0]
        elif s[0] == prev:
            res += (d - 1)
        print(res)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)


def F(S):
    arr = list(S)
    prev = 'A'
    cnt = 0
    for x in S:
        if x == prev:
            cnt += 1
            prev = 'A'
        else:
            prev = x
    return cnt


def main():
    S = input()
    K = int(input())

    arr = [F(S*i) for i in range(10)]

    if K < 10:
        ans = arr[K]
    else:
        if K & 1:
            d = arr[9] - arr[7]
            ans = arr[9] + d * ((K-9)//2)
        else:
            d = arr[8] - arr[6]
            ans = arr[8] + d * ((K-8)//2)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S = input()
K = int(input())
l = len(S)

if l == 1:
    print(K // 2)
    exit()

if l == 2:
    if S[0] == S[1]:
        print(K)
    else:
        print(0)
    exit()



else:
    ans = 0
    prev = None
    edge = False
    for i, v in enumerate(S):
        if prev == v:
            ans += 1
            if i == 0 or i == l - 1:
                edge = True
            prev = None
        else:
            prev = v

    if S[0] != S[-1] or edge:
        print(ans * K)
    else:
        ans2 = 1
        prev = None
        edge2 = False
        for i, v in enumerate(S):
            if i == 0:
                continue
            elif prev == v:
                ans2 += 1
                if i == l - 1:
                    edge2 = True
                prev = None
            else:
                prev = v

        ans3 = 1
        prev = None
        edge3 = False
        for i, v in enumerate(S[::-1]):
            if i == 0:
                continue
            elif prev == v:
                ans3 += 1
                if i == l - 1:
                    edge3 = True
                prev = None
            else:
                prev = v

        if ans2 == ans3 and edge2:
            #print('type2, ans={}, ans2={}, edge2={}'.format(ans, ans2, edge2))
            print((ans + ans2) * (K // 2) + min(ans, ans2) * (K % 2))
        elif ans2 == ans3:
            #print('type3, ans={}, ans2={}, edge2={}'.format(ans, ans2, edge2))
            print(ans + ans2 * (K - 1))
        else:
            print(min(ans2 * K, ans3 * K))

Submission status: Accepted

Solution code:
def main():
    s = list(input())
    k = int(input())
    s.append('-1')
    ran = []
    counter = 0
    while counter < len(s)-1:
        j = counter +1
        while s[counter] == s[j]:
            j += 1
        ran.append([s[counter], j - counter])
        counter = j
    counter = 0
    result = 0
    if k >= 2:
        if len(ran) >= 2:
            if ran[0][0] == ran[-1][0]:
                result += ((ran[0][1]+ran[-1][1])//2)*(k-1)
                if ran[-1][1] != 1:
                    result += ran[-1][1]//2
                if ran[0][1] != 1:
                    result += ran[0][1]//2
            else:
                result += (ran[0][1]//2 + ran[-1][1]//2)*k
        else:
            result += (ran[0][1]*k)//2
        for  i in range(1, len(ran)-1):
            result += ((ran[i][1])//2)*k
        print(result)
    else:
        for i in range(len(ran)):
            result += (ran[i][1])//2
        print(result)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

def solveA(S):
    N = len(S)
    count = 0
    for i in range(N-1):
        if S[i] == S[i+1]:
            S[i+1] = "_"
            count += 1
    return count

def solve(S, K):
    S0 = S[:]
    N = len(S)
    if N == 1:
        return (K-(K%2))//2
    if K < 10:
        return solveA(S*K)
    #actual=(solveA(S*K))
    S1 = S0*1
    S2 = S0*2
    c1 = solveA(S1)
    c2 = solveA(S2)
    if c1 * 2 == c2:
        return c1 * K
    if S2[0] != S2[-1]:
        return c2 * (K//2) + (K%2) * c1
    else:
        a =  c2 * (K//2) + (K%2)*c1 + (K//2)-(1-K%2)
            #if a != solveA(S0*K):
            #print(c1, c2, S2[0]!=S2[-1])
            #print("c2 * (K//2) +(K%2)*c1=", c2 * (K//2)+(K%2)*c1)
        return a


def main():
    S = list(input().rstrip()) # len(S) <= 100
    K = int(input())    # K <= 10**9

    print(solve(S, K))
def test():
    import random

    for i in range(2000):
        n = random.randint(1,100)
        S = random.choices("aaaaaabcedbdddddklkjlkjdsfaak", k=n)
        S0 = S[:]
        K = random.randint(2, 30)
        SK = S*K
        a, a0 = solve(S, K), solveA(SK)
        if a != a0:
            print("".join(S0))
            print(K)
            print("actual=",a, ",expected=",a0)
            print("BAD\n")
            return
#test()
main()

Submission status: Accepted

Solution code:
s=list(input())
k=int(input())
a,b,c=0,0,0
S=s*2
SS=s*3

for i in range(1,len(s)):
    if s[i-1]==s[i]:
        a+=1
        s[i]="A"

for i in range(1,len(S)):
    if S[i-1]==S[i]:
        b+=1
        S[i]="A"
for i in range(1,len(SS)):
    if SS[i-1]==SS[i]:
        c+=1
        SS[i]="A"        

x=a
y=c-a
z=c-b

if k%2==0:
    print(y*((k-2)//2)+x+z)
else:    
    print(y*(k//2)+x)

Submission status: Accepted

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
# input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
# from copy import deepcopy, copy

import queue
from collections import deque




def main():
    s = input()
    k = int(input())

    if len(s) == 1:
        print(k // 2)
        sys.exit()
    if len(s) == 2:
        if s[0] == s[1]:
            print(k)
        else:
            print(0)
        sys.exit()


    s = list(s)
    s2 = []
    for i in range(2):
        for ele in s:
            s2.append(ele)
    s3 = []
    for i in range(3):
        for ele in s:
            s3.append(ele)

    s4 = []
    for i in range(4):
        for ele in s:
            s4.append(ele)

    count = 0
    for i in range(len(s) - 1):
        if s[i + 1] == s[i]:
            s[i + 1] = -1
            count += 1

    count2 = 0
    for i in range(len(s2) - 1):
        if s2[i + 1] == s2[i]:
            s2[i + 1] = -1
            count2 += 1

    count3 = 0
    for i in range(len(s3) - 1):
        if s3[i + 1] == s3[i]:
            s3[i + 1] = -1
            count3 += 1

    count4 = 0
    for i in range(len(s4) - 1):
        if s4[i + 1] == s4[i]:
            s4[i + 1] = -1
            count4 += 1


    if k == 1:
        print(count)
    elif k == 2:
        print(count2)
    elif k == 3:
        print(count3)
    elif k == 4:
        print(count4)
    else:
        if k % 2:
            ans = count2 + ((k - 2) // 2) * (count4 - count2) + (count3 - count2)
        else:
            ans = count2 + ((k - 2) // 2) * (count4 - count2)

        print(ans)








if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys

debug = False

def log(text):
    if debug:
        print(text)

def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
        # for line in sys.stdin:
        #     lines.append(line)
        lines.append(input())
        lines.append(input())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]

    s = lines[0]
    k = int(lines[1])

    return (s, k)


def solve(s, k):

    compress = []
    previous_c = None
    cnt = 1
    for c in s:
        if c == previous_c:
            cnt = cnt + 1
        else:
            if previous_c:
                compress.append((previous_c, cnt))
                cnt = 1
        previous_c = c
    compress.append((previous_c, cnt))
    if debug:
        log("compress=%s" % compress)

    if len(compress) == 1:
        return compress[0][1] * k // 2
    elif len(compress) == 2:
        return (compress[0][1] // 2 + compress[1][1] // 2) * k
        
    head = compress[0]
    if len(compress) > 1:
        body = compress[1:-1]
    else:
        body = []
    tail = compress[-1]
    if debug:
        log("head=%s" % (head,))
        log("body=%s" % (body,))
        log("tail=%s" % (tail,))
    
    body_count = 0 
    for b in body:
        body_count = body_count + b[1] // 2

    total_replace_count = 0
    if head[0] == tail[0]:
        length = head[1] + tail[1]
        replace_count = length // 2 * (k-1)
        total_replace_count = total_replace_count + head[1] // 2 + replace_count + tail[1] // 2
        total_replace_count = total_replace_count + body_count * k
    else:
        total_replace_count = total_replace_count + (head[1] // 2 + body_count + tail[1] // 2) * k

    return total_replace_count


def main():
    # 出力
    result = solve(*parse_input())
    if isinstance(result, list):
        for r in result:
            print("%s" % r, sep='')
    else:
        print("%s" % result, sep='')

if __name__ == '__main__':

    main()

Submission status: Accepted

Solution code:
# coding: utf-8
import math


def solve(*args: str) -> str:
    s = args[0]
    k = int(args[1])

    if all([s[0] == c for c in s]):
        return str(int(len(s) * k / 2))

    H = s[0]

    ret = 0
    h = 0
    t = 0
    if H == s[-1] and 1 < k:
        h = t = 1
        while H == s[h] and h < len(s):
            h += 1

        while H == s[-t-1] and t < len(s):
            t += 1
        ret += int((h + t) / 2) * (k - 1) + int(h/2) + int(t/2)

    ret += count_adjacent_dup(s[h:len(s)-t]) * k

    return str(ret)


def count_adjacent_dup(s: str) -> int:
    ret = 0
    cnt = 0

    for i in range(len(s) - 1):
        if s[i] == s[i+1]:
            cnt += 1
        else:
            ret += math.ceil(cnt/2)
            cnt = 0

    if 0 < cnt:
        ret += math.ceil(cnt/2)

    return ret


if __name__ == "__main__":
    print(solve(*[input() for _ in range(2)]))

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys
import random
import itertools
import math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt


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


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


def LI_(): return list(map(lambda x: int(x)-1, input().split()))


def II(): return int(input())


def IF(): return float(input())


def LS(): return list(map(list, input().split()))


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


def IR(n): return [II() for _ in range(n)]


def LIR(n): return [LI() for _ in range(n)]


def FR(n): return [IF() for _ in range(n)]


def LFR(n): return [LI() for _ in range(n)]


def LIR_(n): return [LI_() for _ in range(n)]


def SR(n): return [S() for _ in range(n)]


def LSR(n): return [LS() for _ in range(n)]


def gcd(x, y):
    if y == 0:
        return x
    return gcd(y, x % y)


def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]


mod = 1000000007
inf = float('INF')


def A():
    S = input()

    K = II()

    if len(S) == 2:
        print(K//2)
        return

    i = 0
    ans = 0
    A = 1
    p = 0
    z=0
    z2=0
    while(A > 0):
        count = 0
        while(S[i] == S[i+1]):
            if i == 0 :
                p = 1
            if S[i+2] == '\n':
                p=2
            count += 1
            i += 1
        if p == 1 :
            z=count+1
        if p==2:
            z2=count+1

        if(S[i] != S[i+1]):
            i += 1
        if count == len(S)-2:
            print(((len(S)-1)*K)//2)
            return

        if count > 0:
            ans += (count+1)//2

        if S[-1] == S[i]:
            A = -1
        p=0
    if K >= 2 and S[-2] == S[0] and S[-3] != S[-2] and S[0] != S[1]:
        ans += 1
        print((ans*K)-1)
    elif K >= 2 and S[-2] == S[0] and (z % 2==1 and z2%2==1):
        ans += 1
        print((ans*K)-1)
    else:
        print(ans*K)

    return

# B


def B():
    N, K = map(int, input().split())
    h = LI()
    count = 0

    for i in h:
        if i >= K:
            count += 1
        else:
            continue
    print(count)
    return

# C


def C():
    N = II()
    A = LI()
    J = [0] * N
    for i, n in enumerate(A):
        J[n-1] = i+1
    for s in J:
        print(s, end=" ")

    return

# D


def D():
    A, B = map(int, input().split())
    g = gcd(A, B)
    # go = g
    # myset = set([1])
    sq = int(sqrt(g)) + 2
    ans = 1

    for i in range(2, sq):
        if g % i == 0:
            ans += 1
        while g % i == 0:
            g /= i

            # myset.add(i)
        if g == 1:
            break
        if i == sq - 1:
            # myset.add(go)
            ans += 1

    print(ans)

    return

# E


def E():
    N, M = LI()
    bit_max = 1 << N
    dp = [[inf for i in range(bit_max)] for j in range(M+1)]
    dp[0][0] = 0

    for i in range(M):
        a, b = LI()

        c = LI()
        bit = 0

        for d in c:
            bit |= 1 << (d-1)

        for w in range(bit_max):

            t = w | bit
            cost = dp[i][w] + a

            dp[i+1][t] = min(dp[i+1][t], cost)

            dp[i+1][w] = min(dp[i][w], dp[i+1][w])

    print(-1) if dp[-1][-1] == inf else print(dp[-1][-1])

    return

# F


def F():
    N, M = LI()

    value = [0] * M
    power = [0] * M
    for i in range(M):
        a, b = LI()
        value[i] = a
        c = LI()
        L = ['0'] * N
        for k in c:
            L[k - 1] = '1'
        bint = ''.join(L)
        power[i] = int(bint, 2)
    bint = ''.join(list(['1'] * N))
    dp = [inf] * (int(bint, 2)+1)
    t = 0
    cost = 0

    dp[0] = 0
    for s in range(int(bint, 2) + 1):
        for i in range(M):
            t = s | power[i]
            cost = dp[s] + value[i]
            dp[t] = min(dp[t], cost)
    print(-1) if(dp[-1] == inf) else print(dp[-1])

    return

    # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")


def solution(S):
    # write your code in Python 3.6
    import math

    vowels = "AIUEO"
    count = 0
    consonants = 0
    newC = []
    newV = []

    for i in S[:-1]:
        if i in vowels:
            count += 1
            newV.append(i)
        else:
            consonants += 1
            newC.append(i)

    if consonants < count or consonants - 2 > count:
        return 0

    a = math.factorial(len(set(newC))) * math.factorial(len(set(newV)))
    return a

    pass


# Solve
if __name__ == '__main__':
    A()

Submission status: Accepted

Solution code:
s=input()
k=int(input())
ans=0
cnt=1
add=False
lead=1
if len(s)==1:
  print(k//2)
  exit()
for i in range(1,len(s)):
  if s[i-1] == s[i]:
    lead+=1
  else:
    break
if len(s)%2 != 0 and s.count(s[0])==len(s):
  print((len(s)*k)//2)
  exit()
for i in range(1,len(s)):
  if s[i-1] == s[i]:
    cnt+=1
  else:
    ans+=cnt//2
    cnt=1
  if s[0] == s[-1] and lead%2!=0 and cnt%2==1 and i == (len(s)-1):
    ans+=cnt//2
    add=True
  elif i == (len(s)-1):
    ans+=cnt//2
if add:
  print((ans*k)+1*(k-1))
else:
  print(ans*k)