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 heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
#ts=time.time()
#sys.setrecursionlimit(10**6)
#input=sys.stdin.readline
show_flg=False
show_flg=True

def naive(b,k):
    a=b*k
    n=len(a)
    p=a[0]
    t=0
    for i in range(n-1):
        if p==a[i+1]:
            t+=1
            p=-1
        else:
            p=a[i+1]
            
    return t

b=StoI()
k=I()

if len(b)*k<10:
    print(naive(b,k))
    exit()

odd=naive(b,3)-naive(b,1)
even=naive(b,4)-naive(b,2)
if k%2==1:
    ans=naive(b,1)+(k//2)*odd
else:
    ans=naive(b,2)+(k//2)*even-even
print(ans)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
#ts=time.time()
#sys.setrecursionlimit(10**6)
#input=sys.stdin.readline
show_flg=False
show_flg=True

def naive(b,k):
    a=b*k
    n=len(a)
    
    p=a[0]
    t=0
    for i in range(n-1):
        if p==a[i+1]:
            t+=1
            p=-1
        else:
            p=a[i+1]
            
    return t


b=StoI()
a=b
k=I()
n=len(a)
p=a[0]
t=0

if len(b)*k<10:
    print(naive(b,k))
    exit()


for i in range(n-1):
    if p==a[i+1]:
        t+=1
        p=-1
    else:
        p=a[i+1]

odd=naive(b,3)-naive(b,1)
even=naive(b,4)-naive(b,2)
if k%2==1:
    ans=naive(b,1)+(k//2)*odd
else:


    ans=naive(b,2)+(k//2)*even-even
print(ans)

Submission status: Accepted

Solution code:
S,K=open(0);K=int(K);s=1;l=[]
for c,d in zip(S,S[1:]):
 if c==d:s+=1
 else:l+=[s];s=1
if len(l)==1:print(l[0]*K//2)
elif S[0]==S[-2]:print(K*sum(i//2for i in l[1:-1]+[l[0]+l[-1]])-(l[0]&l[-1]&1))
else:print(K*sum(i//2for i in l))

Submission status: Accepted

Solution code:
import sys

S = list(input())
K = int(input())
 
T = S + S

flag = 0
c = S[0]
for i in range(len(S) - 1):
    if c != S[i + 1]:
      flag = 1

if flag == 0:
  print(len(S) * K // 2)
  sys.exit()

countA = 0
for i in range(len(S) - 1):
    if S[i] == S[i + 1]:
        countA += 1
        S[i + 1] = 'A'
 
# 2bai
countB = 0
for i in range(len(T) - 1):
    if T[i] == T[i + 1]:
        countB += 1
        T[i + 1] = 'A'
tmp = countB - (2*countA)
print((countA * K) + (tmp * (K - 1)))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, 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)]
mod = 1000000007
inf = float('INF')

#A
def A():
    s = S()
    k = II()
    ans = 0
    lis = []
    i = 0
    tmp = 1
    while len(s) > i + 1:
        if s[i] == s[i + 1]:
            tmp += 1
        else:
            lis.append((s[i], tmp))
            tmp = 1
        i += 1
    lis.append((s[i], tmp))
    if lis[0][0] == lis[-1][0]:
        if len(lis) == 1:
            ans += k * lis[0][1] // 2
            print(ans)
            return
        ans -= (lis[0][1] // 2 + lis[-1][1] // 2) * (k - 1)
        ans += (lis[0][1] + lis[-1][1]) // 2 * (k - 1)
    for _, b in lis:
        ans += b // 2 * k
    print(ans)
    

    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

# coding: utf-8
# Your code here!

s=input()
K=int(input())
S=list(s) #文字を置き換えるためリストに変換

def monomer(A): #文字列内の置換回数を数える関数。引数がリスト。
    N=0
    for i in range(len(A)-1):
        if A[i]==A[i+1]:
            A[i+1]="?"
            N+=1
    return N

n=monomer(S) #文字列S単体内での隣接重複文字、重複を置き換える
if S[0]!=S[-1]: #モノマー内の置き換え後に最初と最後が同じでなければそのまま掛け算でOK
    print(n*K)

#置き換え後も最初と最後が同じ場合は接続ダブりを考慮
else:
    WS=list(s*2) #pppのような、偶数次と奇数次で置換文字が交互に変わるパターン対策
    WS.insert(0,WS[-1]) #ppapのような2次以降に最初の文字を置換した方がいいパターン対策
    wn=monomer(WS)
    SS=list(s)
    SS.insert(0,SS[-1])
    nn=monomer(SS)
    print(n+wn*((K-1)//2)+nn*((K-1)%2)) #最初のループ、途中のループ、最後に余ったループでの置き換え回数

Submission status: Accepted

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

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

count = 1
i = 0
sum = 0
while(1):
    if S[i] == S[i+1]:
        count += 1
        i += 1
    else:
        sum += count//2
        count = 1
        i += 1
    if i == len(S)-1:
        break

sum += count//2 #最後のカウントの加算

#print("check1",sum)

#先頭の連続数をカウント
j = 0 # リストカウント
a = 1 # 連続数カウント
while(1):
    if S[j] == S[j+1]:
        a += 1
        j += 1
    else:
        break
    if j == len(S) -1:
        break
#print("check")

#末尾の連続数をカウント
m = len(S)-1 # リストカウント
b = 1 # 連続数カウント
while(1):
    if S[m] == S[m-1]:
        m -= 1
        b += 1
    else:
        break
    if m == 0:
        break

#print("a is",a)
#print("b is",b)
#print("sum is", sum)
if a == len(S): #１文字のみで文字列構成の場合
    print((len(S)* K)//2)
elif S[len(S)-1] == S[0]:
    print( sum * K + ((a+b)//2 - a//2 - b //2 ) * ( K -1))
else:
    print( sum * K)

Submission status: Accepted

Solution code:
a = lambda x: x//2

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

    l = len(S)
    hoge = [1]+[0]*(l-1)
    for i in range(1,l):
        if S[i] == S[i-1]:
            hoge[i] = hoge[i-1] + 1
            hoge[i-1] = 0
        else:
            hoge[i] = 1
    e = list(filter(lambda x: x,hoge))

    if len(e) == 1:
        return a(e[0]*K)
    elif S[0] == S[-1]:
        beg = e[0]
        end = e[-1]
        e = e[1:-1]
        return a(beg) + sum(map(a,e))*K + a(beg+end)*(K-1) + a(end)
    else:
        return sum(map(a,e))*K

print(main())

Submission status: Accepted

Solution code:
s = str(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:
def count(S):
    ans = 0
    i = 1
    while i < len(S):
        if S[i-1] == S[i]:
            i += 1
            ans += 1
        i += 1
    return ans

def first_last_count(S):
    first = 1
    c = S[0]
    for i in range(1, len(S)):
        if S[i] == c:
            first += 1
        else:
            break

    last = 1
    c = S[0]
    for i in range(len(S)-2, 0, -1):
        if S[i] == c:
            last += 1
        else:
            break

    return (first//2) + (last//2) - ((first+last)//2)

def is_same(S):
    c = S[0]
    for i in range(1, len(S)):
        if S[i] != c:
            return False
    return True

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

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

    ans = count(S)
    ans *= K
    if S[-1] == S[0]:
        ans -= first_last_count(S) * (K-1)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S=input()
S_=S+"A"
K=int(input())
i=0
cnt=0
lst=[]
while i<len(S_)-1:
    if not S_[i] == S_[i+1]:
        cnt+=1
        lst.append(cnt)
        cnt=0
        i+=1
    else:
        i+=1
        cnt+=1
if len(lst)==1:#一種類の時
    print((lst[0]*K)//2)
elif S[0]!=S[-1]:
    ans=0
    for j in lst:
        ans+=j//2
    print(ans*K)
else:
    ans_1=0
    ans_2=0
    for k in range(len(lst)):
        ans_1+=lst[k]//2
    for k in range(len(lst)):
        if k==0:
            ans_2+=lst[k]//2
        elif k==len(lst)-1:
            ans_2+=lst[k]//2
            ans_2+=(lst[k]+lst[0])//2
        else:
            ans_2+=(lst[k]//2)*2
    print(ans_1+(ans_2-ans_1)*(K-1))

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:
import sys

def input(): return sys.stdin.readline()[:-1]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def MATINT(h): return [list(map(int, input().split())) for _ in range(h)]
def MATSTR(h): return [input() for _ in range(h)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
inf = float('inf')
mod = 10 ** 9 + 7

S = input()
K = INT()

N = len(S)
numlist = []
count = 1

for i in range(1, N):
    if S[i] == S[i - 1]:
        count += 1
    else:
        numlist.append(count)
        count = 1
numlist.append(count)
if len(numlist) == 1:
    ans = (N * K) // 2
elif S[0] == S[-1]:
    center = numlist[0] + numlist[-1]
    ans = (center // 2) * (K - 1)
    ans += numlist[0] // 2
    ans += numlist[-1] // 2
    for i in range(1, len(numlist)-1):
        ans += (numlist[i] // 2) * K
else:
    ans = 0
    for i in range(len(numlist)):
        ans += (numlist[i] // 2) * K
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
from collections import Counter

# def f2(s):
#     n = len(s)
#     c = 0
#     ans = 0
#     for i in range(n-1):
#         if s[i] == s[i+1]:
#             c += 1
#             if i == n-2:
#                 ans += (c+1) // 2
#         else:
#             ans += (c+1) // 2
#             c = 0
#     return ans

def f(s):
    n = len(s)
    i = 0
    ans = 0
    while i < n-1:
        c = 0
        while i < n-1 and s[i] == s[i+1]:
            c += 1
            i += 1
        ans += (c+1) // 2
        i += 1
    return ans

def main():
    s = input().strip()
    k = int(input().strip())
    n = len(s)
    if len(Counter(s)) == 1:
        print(n * k // 2)
        return
    ini = f(s)
    dif = f(s*2) - ini
    print(ini + dif * (k-1))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
from collections import Counter

def f(s):
    n = len(s)
    c = 0
    ans = 0
    for i in range(n-1):
        if s[i] == s[i+1]:
            c += 1
            if i == n-2:
                ans += (c+1) // 2
        else:
            ans += (c+1) // 2
            c = 0
    return ans

def main():
    s = input().strip()
    k = int(input().strip())
    n = len(s)
    if len(Counter(s)) == 1:
        print(n * k // 2)
        return
    ini = f(s)
    dif = f(s*2) - ini
    print(ini + dif * (k-1))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s=list(input())
k=int(input())
ss=s*2
a,b=0,0
i=1
while i<len(s):
    if s[i]==s[i-1]:
        i+=2
        a+=1
    else:
        i+=1
i=1        
while i<len(ss):
    if ss[i]==ss[i-1]:
        i+=2
        b+=1
    else:
        i+=1    
if len(set(s))==1:
    print(len(s)*k//2)
else:
    print(a+(b-a)*(k-1))

Submission status: Accepted

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

if len(set(S)) == 1 or len(S) == 1:
    ans = K * len(S) // 2
    print(ans)
    exit()

left = 0
right = 1

while left < N and S[left] == S[0]:
    left += 1
while right <= N and S[-right] == S[-1]:
    right += 1
right -= 1

change = 0
isChanged = False
T = list(S[left: N - right])

for i, t in enumerate(T[1:], start=1):
    if t == T[i - 1]:
        if not isChanged:
            change += 1
            isChanged = True
            continue
    isChanged = False

ans = change * K
if S[0] == S[-1]:
    ans += left // 2 + (left + right) // 2 * (K - 1) + right // 2
else:
    ans += (left // 2 + right // 2) * K

print(ans)

Submission status: Accepted

Solution code:
import sys
s = input()
k = int(input())
ans = []
seqlen = 1
for i in range(len(s)-1):
    if s[i] == s[i+1]:
        seqlen += 1
    else:
        ans.append(seqlen)
        seqlen = 1
ans.append(seqlen)
if len(ans) == 1:
    print(len(s)*k//2)
    sys.exit()
key = 0
key0 = 0
key1 = 0
if s[-1] == s[0]:
    key0, key1 = ans[0], ans[-1]
    ans[0] = ans[0]+ans[-1]
    ans.pop()
    key = 1
for i in range(len(ans)):
    ans[i] = ans[i] // 2
answer = sum(ans)
if key0:
    print(answer*k+key0//2+key1//2-(key0+key1)//2)
else:
    print(answer*k)

Submission status: Accepted

Solution code:
def d_c(s):
  count = 0
  x = ''
  for i in range(len(s)):
    if x == s[0]:
      count += 1
      x = ''
    else:
      x = s[0]
    s = s[1:]
  return count
 
def num_con(s):
  x = s[0]
  s = s[1:]
  count = 1
  for i in range(len(s)):
    if s[0] == x:
      count += 1
      x = s[0]
      s = s[1:]
    else:
      break
  return count
      
    
s = input()
k = int(input())
 
if len(s)==1:
  print(k//2)
elif num_con(s)==len(s):
  print((len(s)*k)//2)
elif s[0]==s[-1]:
  f = num_con(s)
  m = num_con(s[::-1])
  dis = (f//2 + m//2 - (f+m)//2)*(k-1)
  print(d_c(s)*k-dis)
else:
  print(d_c(s)*k)

Submission status: Accepted

Solution code:
s,k = input(),int(input())

chrs = []
prev = 0
cnt = 0
for c in s:
    if c==prev: cnt+=1
    else: chrs.append(cnt);cnt=1
    prev = c
chrs.append(cnt)

ans = 0
for i in chrs: ans += i//2
ans *= k
if s[0]==s[-1]: ans += (chrs[1]%2 and chrs[-1]%2) * (k-1)

if len(set(s))==1: ans = len(s)*k//2

print(ans)

Submission status: Accepted

Solution code:
S = input()
K = int(input())
cnt = 0
ind_f = 0
ind_b = 0
# 全部同じ
import sys
if len(S) == S.count(S[0]):
    print(len(S) * K // 2)
    sys.exit()
# 先頭と後ろ
if S[0] == S[-1]:
    _ = S[0]
    for i, c in enumerate(S):
        if _ != c:
            ind_f = i
            cnt = i
            break
    for i, c in enumerate(S[::-1]):
        if _ != c:
            ind_b = i
            cnt += i
            break
cnt = (cnt // 2) * (K - 1) # 接続部分
cnt += ind_f // 2 + ind_b // 2
prev = ''
cnt2 = 0
if ind_f > 0:
    S = S[ind_f:-ind_b]
for c in S:
    if prev == c:
        cnt2 += 1
        prev = '0'
    else:
        prev = c
cnt += cnt2 * K    
print(cnt)

Submission status: Accepted

Solution code:
from sys import stdin

S = stdin.readline().rstrip()
K = int(stdin.readline().rstrip())
ans_odd = 0
ans_even = 0
changed_odd = [False] * len(S)
changed_even = [False] * len(S)

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

cnt = 1
ans = 0
begin = 0
end = 0

start = 0
for i in range(1, len(S)):
    if S[i - 1] != S[i]:
        if start == 0:
            begin += cnt
        else:
            if cnt >= 2:
                ans += cnt // 2
        cnt = 1
        start = i
    else:
        cnt += 1
    if i == len(S) - 1:
        if start == 0:
            print((cnt * K) // 2)
            exit()
        end += cnt
        break

if S[0] != S[-1]:
    print(ans * K + (begin // 2) * K + (end // 2) * K)
else:
    print(ans * K + begin // 2 + end // 2 + ((begin + end) // 2) * (K - 1))

Submission status: Accepted

Solution code:
S = input()
K = int(input())
li = []
num = 1

#数えるセクション
for i in range(len(S)-1): #もしlen(S)==1の場合、ループは一回も回らない。（エラーもでない？）
    if S[i] == S[i+1]:
        num += 1
    else:
        li.append(num)
        num = 1
li.append(num)
#print(li)

#合計セクション
g = 0
for l in li:
    g += (l // 2)
#print(g)

#解答セクション
tmp = 0
result = 0
if len(li) == 1:
    result = (li[0] * K) // 2
else:
    tmp = sum(j // 2 for j in li)
    if S[0] != S[-1]:
        result = tmp * K
    else:
        if li[0] % 2 == li[-1] % 2 == 1: #最初と最後がどちらも奇数個の連続ならば、プラス1する必要がある。
            result = tmp * K + (1 * (K-1))
        else:
            result = tmp * K

print(result)

Submission status: Accepted

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

# 全部同じ場合
if len(set(list(S))) == 1:
    print(len(S) * K // 2)
    exit()

focus_c = S[0]
consecutive_s = S[0]
focus_s_array = []
for s in S[1:]:
    if s == focus_c:
        consecutive_s += s
    else:
        focus_s_array.append(consecutive_s)
        focus_c = s
        consecutive_s = s
else:
    focus_s_array.append(consecutive_s)


cost = 0
for fsa in focus_s_array:
    cost += len(fsa) // 2
ans = cost * K

if (focus_s_array[0][0] == focus_s_array[-1][0]) and ((len(focus_s_array[0]) + len(focus_s_array[-1])) % 2 == 0):
    ans += K - 1

print(ans)

Submission status: Accepted

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

REPLACED = '_'


def get_start(s):
    i = 1
    while i < len(s):
        if s[0] != s[i]:
            break
        i += 1
    return s[:i]


def replace(s):
    characters = list(s)
    s_length = len(s)
    s_types = len(set(s))

    if s_length == s_types:
        return s

    start = get_start(s)
    if len(start) == 1:
        pass
    elif len(start) % 2 == 0:
        for i in range(0, len(start), 2):
            characters[i] = REPLACED
    else:
        for i in range(1, len(start), 2):
            characters[i] = REPLACED

    i = 0
    while i < s_length - 1:
        chunk = characters[i:i + 3]

        if REPLACED in chunk:
            i += 1
            continue

        chunk_length = len(chunk)
        chunk_types = len(set(chunk))
        if chunk_length == 1:
            break
        elif chunk_length == 2:
            if chunk_types == 2:
                break
            else:
                characters[i + 1] = REPLACED
                break
        elif chunk_length == 3:
            if chunk_types == 3:
                i += 2
                continue
            elif chunk_types == 2:
                if chunk[0] == chunk[1]:
                    characters[i] = REPLACED
                    i += 2
                    continue
                elif chunk[1] == chunk[2]:
                    characters[i + 2] = REPLACED
                    i += 3
                    continue
                else:
                    i += 2
                    continue
            else:
                characters[i + 1] = REPLACED
                i += 2
                continue
        else:
            raise Exception

    return ''.join(characters)


def check(s, k):
    s_length = len(s)
    s_types = len(set(s))
    if (s_types == 1) or (s_length == 1):
        return s_length * k // 2
    elif s_types == s_length:
        return 0
    else:
        replaced_s = replace(s)
        replaced_count = replaced_s.count(REPLACED)
        if replaced_s[0] == replaced_s[-1] and replaced_s[0] != REPLACED:
            return (replaced_count * k) + (k - 1)
        else:
            return replaced_count * k


print(check(S, K))

Submission status: Accepted

Solution code:
s = input()
k = int(input())
c = 0
d = 0
a = []
s += "A"
for i in range(len(s)-1):
    if (s[i] == s[i+1]):
        c += 1
    else:
        a.append(c+1)
        d += 1
        c = 0
c = 0
if s[0] != s[len(s)-2]:
    for i in range(d):
        c += a[i]//2
    print(int(c*k))
elif d == 1:
    print(int(a[0]*k//2))
else:
    for i in range(d):
        c += a[i]//2
    c = c*k - (k-1)*(a[0]//2 + a[d-1]//2 - (a[0] + a[d-1])//2)
    print(int(c))

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

S = str(input())
n = len(S)
K = I()

num = 0
flag = False
for i in range(1,n):
    if S[i]==S[i-1] and flag==False:
        num += 1
        flag = True
    else:
        flag = False

if flag==False and S[0]==S[-1]:
    num2 = 1
    flag2 = False
    for i in range(2,n):
        if S[i]==S[i-1] and flag2==False:
            num2 += 1
            flag2 = True
        else:
            flag2 = False
    if n==1:
        flag2 = True
    if flag2==False:
        print(num+num2*(K-1))
        exit()
    else:
        print(num2*(K//2) + num*(K-K//2))
        exit()
else:
    print(num*K)

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:
from itertools import groupby

s = input()
k = int(input())

t = [(k, len(list(v))) for k, v in groupby(s)]
ans = 0
if len(t) == 1:
    ans += t[0][1] * k // 2
else:
    if t[0][0] == t[-1][0] and t[0][1] % 2 == 1 and t[-1][1] % 2 == 1:
        ans += k - 1
    ans += sum(v[1] // 2 for v in t) * k
print(ans)

Submission status: Accepted

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

if len(set(S)) == 1 or len(S) == 1:
    ans = K * len(S) // 2
    print(ans)
    exit()

left = 0
right = 1

while left < N and S[left] == S[0]:
    left += 1
while right <= N and S[-right] == S[-1]:
    right += 1
right -= 1

change = 0
isChanged = False
T = list(S[::])

for i, t in enumerate(T[1:], start=1):
    if t == T[i - 1]:
        if not isChanged:
            change += 1
            isChanged = True
            continue
    isChanged = False

ans = change * K

if S[0] == S[-1]:
    ans -= (left // 2 - (left + right) // 2 + right // 2) * (K - 1)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

    d = [[s[0], 1]]
    for i in range(1, len(s)):
        if s[i] == d[-1][0]:
            d[-1][1] += 1
        else:
            d.append([s[i], 1])
    
    if len(d) == 1:
        print((len(s) * k) // 2)
    else:
        ans = 0
        for c, count in d:
            ans += count // 2
        ans *= k
        if d[0][0] == d[-1][0]:
            a = d[0][1]
            b = d[-1][1]
            ans -= ((a//2) + (b//2) - ((a+b)//2)) * (k-1)
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def a_connection_and_disconnection():
    from itertools import groupby
    S = input()
    K = int(input())

    # 連続した文字がn個あるなら、そのうちn//2個を変更しないといけない(基本)
    # 後にS中に現れる文字の種類が2以上であることを仮定する処理があるため、ここで分岐
    if len(set(S)) == 1:
        return len(S) * K // 2

    # S に対してランレングス圧縮に似たことをする(文字が何であるかは問わない)
    counter = [len(list(g)) for _, g in groupby(S)]
    # この式では、Sの先頭と末尾を結合したときに同じ文字が連続するかを考えない
    ans = sum([c // 2 for c in counter]) * K

    # Sの先頭と末尾が同じ文字の場合、上の式について
    # ・先頭と末尾を独立に計算してしまった分は引く(そんな部分はK-1箇所ある)
    # ・先頭と末尾を結合した分は足す(そんな部分はK-1箇所ある)
    # ということを反映したのが3つ目の式
    if S[0] == S[-1]:
        a, b = counter[0], counter[-1]
        ans -= (a // 2 + b // 2 - (a + b) // 2) * (K - 1)
    return ans

print(a_connection_and_disconnection())

Submission status: Accepted

Solution code:
def main():
    S = input()
    N = len(S)
    K = int(input())

    if K == 1:
        print(cnt(S))
        return
    if K == 2:
        print(cnt(S*2))
        return
    i = 0
    j = 0
    while True:
        if S[i] != S[(j-1) % N]:
            break
        i += 1
        j = (j + 1) % N
        if i >= N:
            i = -1
            break
    if i == -1:
        print(K * N // 2)
        return
    start = S[:i]
    end = S[j:]
    mid = S[i:] + S[:j]
    # print(start)
    # print("1")
    # print(end)
    # print("w")
    # print(mid)
    print(cnt(start) + cnt(mid) * (K-1) + cnt(end))


def cnt(S):
    prev = "あ"
    cnt = 0
    for c in S:
        if c == prev:
            cnt += 1
            prev = "あ"
        else:
            prev = c
    return cnt
main()

Submission status: Accepted

Solution code:
S = input()
K = int(input())
d=[[0 for _ in range(400)] for _ in range(4)]
ans = [0,0,0,0]
l = len(S)
odd_diff = 0
even_diff = 0
if l == 1:
    print(int(K//2))
if l > 1:
    for i in range(4):
        s = S * (i + 1)
        l = len(s)
        for j in range(l-1):
            
            if j == 0 and s[j] == s[j+1]:
                ans[i] += 1
                d[i][0] = 1
            if j > 0 and s[j] == s[j+1] and d[i][j-1] == 0:
                ans[i] += 1
                d[i][j] = 1
    if K <= 4:
        print(int(ans[K-1]))
    elif K > 4 and K % 2 == 0:
        even_diff = ans[3] - ans[1]
        print(int(ans[1]+(K/2-1)*even_diff))
    elif K > 4 and K % 2 == 1:
        odd_diff = ans[2] - ans[0]
        print(int(ans[0]+(K//2)*odd_diff))

Submission status: Accepted

Solution code:
#O(2n)程度を見込む解答
s=input()
k=int(input())
ss=s+s
n=len(s)

ppp=1
for i in range(n-1):
	if s[i]!=s[i+1]:
		ppp=0
		break
		
if ppp==1:
	print(n*k//2)
else:		
	counts=0
	i=0
	while i<n-1:
		if s[i]!=s[i+1]:
			i+=1
		else:
			i+=2
			counts+=1
			
	countss=0
	i=0
	while i<n*2-1:
		if ss[i]!=ss[i+1]:
			i+=1
		else:
			i+=2
			countss+=1
			
	if countss==counts*2:
		print(counts*k)
	else:
		print(counts*k+k-1)