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:
def main():
    s = input()
    k = int(input())

    count_l = []
    i = 0
    counter = 1
    while True:
        if len(s) == 1:
            count_l.append(counter)
            break
        elif s[i] == s[i+1]:
            counter += 1
        else:
            count_l.append(counter)
            counter = 1
        i += 1
        if i == len(s)-1:
            if counter == 1:
                break
            else:
                count_l.append(counter)
                break

    answer = 0
    if len(count_l) >= 3 and s[0] == s[-1] and k >= 2:
        sub_l = [count_l[0] + count_l[-1]] + count_l[1:-1]
        for i in range(len(sub_l)):
            answer += (sub_l[i] // 2) * (k - 1)
        for j in range(len(count_l[:-1])):
            answer += count_l[j] // 2
        answer += count_l[-1] // 2
    elif len(count_l) == 1:
        answer += (count_l[0] * k) // 2
    else:
        for i in range(len(count_l)):
            answer += (count_l[i] // 2) * k

    print(answer)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = input()
k = int(input())
n = len(s)
renzoku_flag =False
renzoku_count = 0
count = 0
for i in range(n):
    if i != n-1:
        if s[i] == s[i+1]:
            renzoku_count += 1 #iのをカウントしている
        else:
            renzoku_count += 1 #i+1の分をカウント
            count += renzoku_count // 2
            renzoku_count = 0
    else:
        if s[n-2] == s[n-1]:
            renzoku_count += 1
        count += renzoku_count // 2

if s[0] != s[-1]:
    print(count*k)
else:
    ans = count*k
    initial = s[0]

    start_count = 0
    for i in range(n):
        if s[i] == initial:
            start_count += 1
        else:
            break
    else:
        print(n*k//2)
        exit()

    end_count = 0
    for i in range(n)[::-1]:
        if s[i] == initial:
            end_count += 1
        else:
            break

    ans -= (start_count//2 + end_count//2 - (start_count+end_count)//2)*(k-1)
    print(ans)

Submission status: Accepted

Solution code:
import math
S = input()
K = int(input())
s = list(S)
c1 = 0
for i in range(len(s)-1):
    if s[i+1] == s[i]:
        c1 += 1
        s[i+1] = 0
s = list(S*2)
c2 = 0
for i in range(len(s)-1):
    if s[i+1] == s[i]:
        c2 += 1
        s[i+1] = 0
c = S[0]
for s in S:
    if s != c:
        print(c1+(c2-c1)*(K-1))
        exit()
print(math.floor(len(S)*K/2))

Submission status: Accepted

Solution code:
s=list(input()) ;k=int(input()) ;n=len(s)
ss=s*2
import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict #すべてのkeyが用意されてる defaultdict(int)で初期化
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal as D  #変換後の末尾桁を0や0.01で指定
  #Decimal((str(0.5)).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
from functools import lru_cache
from bisect import bisect_left as bileft, bisect_right as biright
from fractions import Fraction as F  #F(a,b)で正確なa/b
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#ソート、"a"+"b"、再帰ならPython3の方がいい
#######ここから天ぷら########


if n==1:
    print(k//2);exit()

def qq(s,n):
    ans=0
    if n==2:
        if s[0]==s[1]:return 1
        return 0
    nows=s[0];now=1
    for i in range(1,n):
        if s[i]==nows:
            now+=1
        else:
            ans+= now//2
            now=1 ;nows=s[i]
    else:
        ans+=now//2
    return ans 

if len(Counter(s))==1:
    print((n*k)//2)
    exit()
if s[0]!=s[-1]:
    print(qq(s,n)*k)
    exit()
st=1; go=1
for i in range(1,n):
    if s[i]==s[0]:
        st+=1
    else:
        break
for i  in range(-2,-n-1,-1):
    if s[i]==s[-1]:
        go+=1
    else:break
print(qq(s,n)*k - (st//2+go//2-(st+go)//2)*(k-1))

Submission status: Accepted

Solution code:
s=input()
n=len(s)
k=int(input())
if s[0]==s[n-1]:
  d=1
  ans=0
  for i in range(1,n):
    if s[i-1]==s[i] and d==1:
      ans+=1
      d=0
    elif s[i-1]==s[i] and d==0:
      d=1
    elif s[i-1]!=s[i]:
      d=1
  if d==0:
    print(ans*k)
  else:
    ans2=0
    for i in range(n):
      if s[i-1]==s[i] and d==1:
        ans2+=1
        d=0
      elif s[i-1]==s[i] and d==0:
        d=1
      elif s[i-1]!=s[i]:
        d=1
    if d==1:
      print(ans+ans2*(k-1))
    else:
      if k%2==0:
        print((ans+ans2)*k//2)
      else:
        print((ans+ans2)*(k//2)+ans)
elif s[0]!=s[n-1]:
  d=1
  ans=0
  for i in range(1,n):
    if s[i-1]==s[i] and d==1:
      ans+=1
      d=0
    elif s[i-1]==s[i] and d==0:
      d=1
    elif s[i-1]!=s[i]:
      d=1
  print(ans*k)

Submission status: Accepted

Solution code:
s = input()
t = int(input())
v = set(s)

ans = 0
if len(v) == 1:
  ans = (len(s)*t)//2
  print (ans)
  exit()

a = []
o = s[0]
c = 0

for i in range(len(s)):
  if o == s[i]:
    c += 1
  else:
    a.append([o,c])
    c = 1
    o = s[i]
a.append([o,c])

for i,j in a:
  if j == 1:
    continue
  ans += (j//2)*t

if len(v) > 1:
  if a[0][0] == a[-1][0]:
    if a[0][1]%2 == 1 and a[-1][1]%2 == 1:
      ans += t-1

print (ans)

Submission status: Accepted

Solution code:
# A - Connection and Disconnection
S = input()
K = int(input())
S = S + '1'# 番兵

# 連続する文字数をカウント
cnt = []
conti = 1
for i in range(1,len(S)):
    if S[i-1] == S[i]:
        conti += 1
    else:
        cnt.append(conti)
        conti = 1
        
# 最初と最後の文字が同じときの補正値
comp = 0
if S[0] == S[-2]:
    # 奇数個 + 奇数個のとき
    if cnt[0]%2 == 1 and cnt[-1]%2 == 1:
        comp = K - 1
    # S =aaa などのとき
    if len(set(S[:-1])) == 1 and len(S[:-1])%2 == 1:
        comp = K // 2
        
ans = [a//2 for a in cnt if a >= 2]
ans = sum(ans)*K + comp
print(ans)

Submission status: Accepted

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

prev = S[0]
cnt = 0
for i in range(1,len(S)):
    if prev == S[i]:
        cnt += 1
        prev = "$"
        continue
    prev = S[i]

ans = k*cnt

if S[0] == S[-1]:
    m = 0
    for s in S:
        if s == S[0]:
            m += 1
        else:
            break
    a = 0
    for s in S[::-1]:
        if s == S[-1]:
            a += 1
        else:
            break
    if a%2 and m%2:
        ans += k-1
if len(set(S)) == 1:
    ans = (len(S)*k//2)
print(ans)

Submission status: Accepted

Solution code:
from itertools import groupby
s = input()
k = int(input())
if len(set(s)) == 1:
    print(len(s)*k//2)
    exit()
g = [len(list(v)) for _, v in groupby(s)]
ans = sum(i//2 for i in g)*k
if s[0] != s[-1]:
    print(ans)
    exit()
a, *_, b = g
ans -= (a//2 + b//2 - (a+b)//2)*(k-1)
print(ans)

Submission status: Accepted

Solution code:
s = input()
k = int(input())
di = []
cnt = 1
ans = 0
if len(s) > 1:
    for i in range(1,len(s)):
        if s[i] == s[i-1]:
            cnt += 1
        else:
            di.append(cnt)
            cnt = 1
    di.append(cnt)
    if di[0] != len(s):
        for j in di:
            ans += j//2
        ans *= k
        if s[0] == s[-1] and di[-1] % 2 == 1 and di[0] % 2 == 1:
            ans += k - 1
    else:
        ans = k*len(s)//2
else:
    ans = k//2
print(ans)

Submission status: Accepted

Solution code:
import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
    s = S()
    k = I()
    same = len(set(list(s)))==1
    ans = None

    if same:
        ans = len(s)*k//2
    else:
        if s[0]!=s[-1]:
            cnt = 0
            change = False
            for i in range(1,len(s)):
                if s[i] == s[i-1] and not change:
                    cnt += 1
                    change = True
                else:
                    change = False
            ans = cnt*k
        else:
            char = s[0]
            start = len(s)
            goal = -1
            cnt = 0
            while s[start-1] == char:
                start -= 1
            while s[goal+1] == char:
                goal += 1
            lenth = len(s)-start + goal+1
            cnt += lenth//2 * (k-1)

            ccnt = 0
            change = False
            for i in range(goal+1+1,start):
                if s[i] == s[i-1] and not change:
                    ccnt += 1
                    change = True
                else:
                    change = False
            cnt += ccnt * (k-2)

            ccnt = 0
            change = False
            for i in range(1,start):
                if s[i] == s[i-1] and not change:
                    ccnt += 1
                    change = True
                else:
                    change = False
            cnt += ccnt

            
            ccnt = 0
            change = False
            for i in range(goal+1+1, len(s)):
                if s[i] == s[i-1] and not change:
                    ccnt += 1
                    change = True
                else:
                    change = False
            cnt += ccnt
            ans = cnt
    print(ans)
                
main()

Submission status: Accepted

Solution code:
s=input()
n=int(input())
if len(s)==1:print(n//2);exit()
if len(set(s))==1:print(len(s)*n//2);exit()
c=1
l=[]
for x in range(1,len(s)):
    if s[x-1]==s[x]:
        c+=1
        if x==len(s)-1:l.append(c)
    else:l.append(c);c=1

t=0
if s[0]==s[-1] and l[0]%2==1 and l[-1]%2==1:t=n-1
print(sum([i//2 for i in l])*n+t)

Submission status: Accepted

Solution code:
s = input()
k = int(input())
ans = 0
s2 = s[0]
for i in range(len(s) - 1):
  if s2[i] == s[i + 1]:
    s2 += '9'
    ans += 1
  else:
    s2 += s[i + 1]
ans = ans * k 
if s2[0] == s2[-1] and len(s) >= 2:
  m = 0
  for i in range(len(s)):
    if s[i] == s2[-1]:
      m += 1
    else:
      break
  if m % 2 == 1:
    ans += k - 1
if len(s) == 1:
  ans = k // 2
if len(list(set(list(s)))) == 1:
  ans = len(s) * k // 2
print(ans)

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
n = len(s)

ans = 0

# すべて同じ文字の場合
if s == [s[0]] * n:
    print((n*k)//2)
    exit(0)

# 先頭と末尾が異なる場合
i = 1
while i < n:
    if s[i-1] == s[i]:
        t = 2
        i+=1
        while i < n and s[i-1] == s[i]:
            t+=1
            i+=1
        ans += (t//2)*k
    i+=1
if s[0] != s[-1]:
    print(ans)
    exit(0)
# 先頭と末尾が一致する場合
# まず不一致の場合と同様に数えて、左右端の連続長さを数える
# 連結したとき、左右の1ブロックのみはそのまま数えられる
# 残りのk-1ブロックは、左右がつながった形で数えられる
i = 1
left = 1
right = 1
for i in range(n):
    if s[i] == s[i+1]:
        left += 1
    else:
        break
for i in range(n-1, -1, -1):
    if s[i] == s[i-1]:
        right += 1
    else:
        break
if s[0] == s[-1]:
    ans = ans - (k-1) * (left//2 + right//2) + (k-1) * ((left+right)//2)
    print(ans)

Submission status: Accepted

Solution code:
s = input()
k = int(input())
ans = 0
soui = 0
moji = s[0]

for i in range(1,len(s)):
    if s[i] == s[i-1] and soui == 0:
        ans += 1
        soui = 1
    elif soui == 1:
        soui = 0


flag = 0
a = 0
b = 0

while s[0] == s[a] and a != len(s)-1:
    a += 1

while s[len(s)-1-b] == s[len(s)-1] and b != len(s)-1:
    b += 1


if s[0] == s[len(s)-1]:
    flag = 1

for i in range(len(s)):
    if moji != s[i]:
        break
    elif i == len(s)-1:
        flag = 2

if flag == 1:
    print((k*ans)-((k-1)*((a//2)+(b//2)-((a+b)//2))))
elif flag == 2:
    print((k*len(s))//2)
else:
    print(k*ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

s = list(input())
k = readInt()

if len(Counter(s))==1:
	ans = k*len(s)//2
elif s[0]!=s[-1]:
	ans = 0
	i = 0
	l = 0
	tmp = s[:]+["!"]
	d = []
	while i<len(s):
		if tmp[i]==tmp[i+1]:
			i+=1
		else:
			d.append(tmp[l:i+1])
			l = i+1
			i+=1
	for i in d:
		ans+=len(i)//2
	ans*=k
else:
	ans = 0
	i = 0
	l = 0
	tmp = s[:]+["!"]
	d = []
	while i<len(s):
		if tmp[i]==tmp[i+1]:
			i+=1
		else:
			d.append(tmp[l:i+1])
			l = i+1
			i+=1
	for i in d[1:-1]:
		ans+=len(i)//2
	ans*=k
	ans+=len(d[0])//2
	ans+=len(d[-1])//2
	ans+=(len(d[0])+len(d[-1]))//2*(k-1)


print(ans)

Submission status: Accepted

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

if list(s[0]*len(s))==s:
	#print('a')
	print(len(s)*k//2)
	exit()

res = [1]
for i in range(len(s)-1):
	if s[i]==s[i+1]:
		res[-1] += 1
	else:
		res.append(1)
ans = 0
for i in res:
	ans += (i//2)*k
if s[0]==s[-1]:
	diff = (res[0]+res[-1])//2 -(res[0]//2 + res[-1]//2)
	ans += diff*(k-1)
print(ans)

Submission status: Accepted

Solution code:
import math
S = list(input())
K = int(input())
s = S * 2
c1 = 0
c2 = 0
for i in range(len(s)-1):
    if s[i+1] == s[i]:
        if i < len(S)-1:
            c1 += 1
        c2 += 1
        s[i+1] = 0
c = S[0]
for s in S:
    if s != c:
        print(c1+(c2-c1)*(K-1))
        exit()
print(math.floor(len(S)*K/2))

Submission status: Accepted

Solution code:
from collections import Counter
def dd(S):
    S += "#"
    s0 = S[0]
    cnt, r = 1, 0
    for s in S[1:]:
        if s == s0:
            cnt += 1
        else:
            r += cnt // 2
            cnt = 1
        s0 = s
    return r
S = input().rstrip()
K = int(input())
s = dd(S)
t = dd(S*2)
if len(Counter(S))==1:
    print(len(S)*K//2)
else:
    print(s*K + (t-2*s)*(K-1))
"""
aaa
3
"""

Submission status: Accepted

Solution code:

def solve(S,K):
    if all(S[0]==c for c in S):
        return (len(S)*K)//2

    if S[0] == S[-1]:
        cnt0 = 0
        for c in S:
            if c == S[0]:
                cnt0 += 1
            else:
                break
        cnt1 = 0
        for c in reversed(S):
            if c == S[0]:
                cnt1 += 1
            else:
                break
        res = cnt0//2 + cnt1//2 - (cnt0+cnt1)//2
        S = S[cnt0:]+S[:cnt0]
    else:
        res = 0

    t = 0
    k = 0
    last = S[0]
    for c in S:
        if c == last:
            k += 1
        else:
            t += k//2
            k = 1
            last = c
    t += k//2
    res += t*K
    return res

S = input()
K = int(input())
print(solve(S,K))

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil,pi,factorial
    from operator import itemgetter
    def I(): return int(input())
    def MI(): return map(int, input().split())
    def LI(): return list(map(int, input().split()))
    def LI2(): return [int(input()) for i in range(n)]
    def MXI(): return [[LI()]for i in range(n)]
    def SI(): return input().rstrip()
    def printns(x): print('\n'.join(x))
    def printni(x): print('\n'.join(list(map(str,x))))
    inf = 10**17
    mod = 10**9 + 7
#main code here!
    s=SI()
    k=I()
    u=len(s)
    seq=0
    x=1
    for i in range(u-1):
        if s[i]==s[i+1]:
            x+=1
        else:
            seq+=x//2
            x=1
    seq+=x//2
    #print(seq)
            
    a=1
    for i in range(u-1):
        if s[0]==s[i+1]:
            a+=1
        else:
            break
    b=1
    for i in range(u-1):
        if s[-1]==s[u-1-(1+i)]:
            b+=1
        else:
            break
    #print(a,b)
    if x==u:
        ans=(u*k)//2
    else:
        if s[0]!=s[-1]:
            ans=(seq)*k
        else:
            ans=(seq)*k-(a//2+b//2-(a+b)//2)*(k-1)
    print(ans)
        





if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
S=input()
K=int(input())
import copy
num=1
liS=[]

for i in range(len(S)-1):
    if S[i]==S[i+1]:
        num+=1
    else:
        liS.append(num)
        num=1
liS.append(num)



liSR=copy.copy(liS)
liSR[0]+=liSR[-1]
del liSR[-1]



if liSR!=[] and S[0]==S[-1]:
    for j in range(len(liS)):
        liS[j]=liS[j]//2
    for k in range(len(liSR)):
        liSR[k]=liSR[k]//2

    print(sum(liSR)*(K-1)+sum(liS))

elif liSR!=[] and S[0]!=S[-1]:
    for j in range(len(liS)):
        liS[j]=liS[j]//2
    print(sum(liS)*K)

else:
    print((sum(liS)*K)//2)

Submission status: Accepted

Solution code:
def solver(s, k):
    res = 0
    cnt = [1]
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            cnt[-1] += 1
        else:
            cnt.append(1)
    for x in cnt:
        res += (x // 2) * k

    if len(cnt) == 1: #全部同じ場合はここでおわり
        return (len(s) * k) // 2

    if s[0] == s[-1]:
        res -= (cnt[0] // 2) * (k - 1) + (cnt[-1] // 2) * (k - 1)
        res += ((cnt[0] + cnt[-1]) // 2) * (k - 1)
    return res

def solver2(s, k):
    t = []
    for _ in range(k):
        t += s
    res = 0
    cnt = 1
    for i in range(1, len(t)):
        if t[i] == t[i - 1]:
            cnt += 1
        else:
            res += cnt // 2
            cnt = 1
    res += cnt // 2
    return res

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

#ss = s
#kk = k
print(solver(s, k))
#print(solver2(ss, kk))

#　ランダムな英小文字列の生成
import random
import string

# n := 文字列の長さ
def randomCharacter(n):
   alphabet_m = string.ascii_lowercase
   return ''.join([random.choice(alphabet_m) for _ in range(n)])


#for i in range(40):
#    if i == 0:
#        st = 'aaaaaaaaa'
#    elif i == 1:
#        st = 'a'
#    else:
#        l = random.randrange(1, 10)
#        st = randomCharacter(l)
#    sstt = st
#    cnt = 4
#    cnst_st = st[:]
#    res1 = solver(st, cnt)
#    res2 = solver2(sstt, cnt)
#    if res1 == res2:        
#        print("OK!")
#    else:
#        print(''.join(cnst_st), res1, res2)

Submission status: Accepted

Solution code:

def main():
    s = list(input())
    k = int(input())
    lst = []
    cnt = 1
    flg = 0
    ans = 0
    prev = s[0]
    for i in range(1, len(s)):
        if prev == s[i]:
            cnt += 1
        else:
            lst.append(cnt)
            cnt = 1
            prev = s[i]
            flg = 1
    lst.append(cnt)
    if len(lst) == 1:
        ans = len(s) * k // 2
    else:
        ans += sum(map(lambda x: x // 2, lst[1:len(lst)-1])) * k
        # for l in lst[1: len(lst) - 1]:
        #     ans += l // 2 * k
        if s[-1] == s[0]:
            ans += (lst[0] + lst[-1]) // 2 * (k - 1)
            ans += lst[0] // 2 + lst[-1] // 2
        else:
            ans += (lst[0] // 2 + lst[-1] // 2) * k
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:


def main():
    s = list(input())
    k = int(input())
    lst = []
    cnt = 1
    flg = 0
    ans = 0
    prev = s[0]
    for i in range(1, len(s)):
        if prev == s[i]:
            cnt += 1
        else:
            lst.append(cnt)
            cnt = 1
            prev = s[i]
            flg = 1
    lst.append(cnt)
    if len(lst) == 1:
        ans = len(s) * k // 2
    else:
        ans += sum(list(map(lambda x: x // 2, lst[1:len(lst)-1]))) * k
        # for l in lst[1: len(lst) - 1]:
        #     ans += l // 2 * k
        if s[-1] == s[0]:
            ans += (lst[0] + lst[-1]) // 2 * (k - 1)
            ans += lst[0] // 2 + lst[-1] // 2
        else:
            ans += (lst[0] // 2 + lst[-1] // 2) * k
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = input()
k = int(input())
n = len(s)
l = [1]*n
'''
S = set(s)
n1 = len(s)
n2 = len(S)
l = [0]*n1

for i in range(n2):
    for j in range(n1):
        temp = 0
        chk = 0
        if s[i] == s[j]:
            l[chk] += 1
        else:
            chk += 1
'''

chk = 0
temp = 0
for i in range(n-1):
    if s[i+1] == s[i]:
        l[chk] += 1
    else:
        chk += 1

if s[0] == s[n-1]:
        temp = 1

memo = 0
edge = 0
ans = 0
for i in range(n-1,-1,-1):
    if l[i] != 1 and memo == 0 and temp == 1:
        memo += 1
        edge = i
    ans += k*(l[i]//2)

if temp == 1 and edge != 0: 
    if (l[0] + l[edge]) % 2 == 0 and l[0] % 2 == 1:
        ans += k-1
elif temp == 1:
    if l[0] % 2 == 1:
        ans += k//2
if n == 1:
    ans = k//2

print(ans)

Submission status: Accepted

Solution code:
S=input()
K=int(input())
ans=0
last=S[0]
cnt=1
if len(set(S))>1:
    for i in range(1,len(S)):
        if S[i]==last:
            cnt+=1
        else:
            ans+=cnt//2
            cnt=1
            last=S[i]
    ans+=cnt//2
    ans*=K
    if S[0]==S[-1]:
        a,b=0,0
        last=S[0]
        for i in range(len(S)):
            if last==S[i]:
                a+=1
            else:
                break
        S=S[::-1]
        for i in range(len(S)):
            if last==S[i]:
                b+=1
            else:
                break
        ans-=(a//2+b//2-(a+b)//2)*(K-1)
else:
    ans=len(S)*K//2
print(ans)

Submission status: Accepted

Solution code:
s = input(); k = int(input())
a = 0
def count(t):
    i = 1; x = 0
    while i < len(t):
        if t[i-1] == t[i]:
            x += 1
            i += 1
        i += 1
    return x
for i in range(len(s)-1):
    if s[i] != s[i+1]: break
else: a = 1
if a == 1: print(len(s)*k//2)
else:
    if k == 1: print(count(s))
    else:
        ss = s+s; sss = ss+s
        print(count(ss)+(count(sss)-count(ss))*(k-2))

Submission status: Accepted

Solution code:
S=input()
k=int(input())
x=1
L=[]
for i in range(len(S)-1):
  if S[i]==S[i+1]:
    x+=1
  else:
    L.append(x)
    x=1
L.append(x)
s=sum([l//2 for l in L])
if S[0]!=S[-1]:
  print(s*k)
else:
  if len(L)>1:
    L[0]+=L[-1]
    print(s+sum([l//2 for l in L[:-1]])*(k-1))
  else:
    print(L[0]*k//2)

Submission status: Accepted

Solution code:
from math import floor
s = input()
k = int(input())
if len(set(s)) == 1:
    print(floor(len(s) * k / 2))
    exit(0)
x = s[0]
y = 1
ans = 0
for i in s[1:]:
    if i == x:
        y += 1
    else:
        ans += floor(y / 2)
        x = i
        y = 1
ans += floor(y / 2)
if s[0] != s[-1]:
    print(ans * k)
else:
    x = s[0]
    y = 1
    for i in s[1:]:
        if x == i:
            y += 1
        else:
            a = y
            break
    y = 0
    for i in s[::-1]:
        if x == i:
            y += 1
        else:
            b = y
            break
    print(ans * k - ((floor(a / 2) + floor(b / 2) - floor((a + b) / 2)) * (k - 1)))

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
n = len(s)

if s == [s[0]]*n:
    print(n*k//2)
else:
    ss = s*2
    ans1 = 0
    for i in range(1, n):
        if s[i] == s[i -1]:
            s[i] = ""
            ans1 += 1
    ans2 = 0
    for i in range(1, 2*n):
        if ss[i] == ss[i - 1]:
            ss[i] = ""
            ans2 += 1
    j = ans2 - ans1
    print(ans1 + j*(k - 1))

Submission status: Accepted

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

vals = []
cur = s[0]
strk = 1

for i in range(1, len(s)):
    if s[i] == cur:
        strk += 1
    else:
        vals.append([cur, strk])
        cur = s[i]
        strk = 1
vals.append([cur, strk])

if len(vals) == 1:
    print((vals[0][1] * k) // 2)
else:
    if vals[0][0] == vals[-1][0]:
        start = vals[0][1] // 2
        join = (vals[0][1] + vals[-1][1]) // 2
        end = vals[-1][1] // 2

        middle = 0
        for i in range(1, len(vals)-1):
            middle += vals[i][1] // 2

        print(start + k*middle + (k-1)*join + end)
    else:
        cnt = 0
        for val in vals:
            cnt += (val[1]) // 2

        print(cnt*k)

Submission status: Accepted

Solution code:
# A - Connection and Disconnection
def count(s, c):
	count_ = s.count(c*2)
	
	while c*3 in s:
		s = s.replace(c*3, c+'_'+c)
	
	while c*2 in s:
		s = s.replace(c*2, c+'_')
	
	return min(count_, s.count('_'))


def get_startswith(s, c):
	key = c
	
	while s.startswith(key+c):
		key += c
	
	return len(key)
	
	
def get_endswith(s, c):
	key = c
	
	while s.endswith(key+c):
		key += c
	
	return len(key)


import string

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

lower = string.ascii_lowercase
ans = 0

if S[0] == S[-1:]:
	start = get_startswith(S, S[0])
	end = get_endswith(S, S[0])	
	
	if start == end == len(S):
		print(len(S) * K // 2)
	else:
		ans = 0
		
		ans += start // 2
		ans += end // 2
		ans += ((start + end) // 2) * (K - 1)
		
		for c in lower:
			ans += count(S[start:len(S)-end], c) * K

		print(ans)	
else:
	for c in lower:
		ans += count(S, c)

	print(ans * K)

Submission status: Accepted

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

if len(set(list(s))) == 1:
    print(len(s)*k//2)
    exit()

tmp = []
cnt = 1

for i in range(1, len(s)):
    if s[i] == s[i-1]:
        cnt += 1
    else:
        tmp.append(cnt)
        cnt = 1

tmp.append(cnt)

if s[0] != s[-1]:
    ans = [i//2 for i in tmp]
    print(sum(ans) * k)
else:
    a = tmp[0]//2
    b = (tmp[0] + tmp[-1])//2
    c = tmp[-1]//2
    ans = [i//2 for i in tmp[1:-1]]
    print(a+sum(ans)*k+b*(k-1)+c)

Submission status: Accepted

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

if s == (s[0]*len(s)):
    print((len(s)*K)//2)

elif s[0] == s[-1]:
    front = 0
    back = len(s)-1
    for i in range(len(s)-1):
        if s[i] is s[i+1]:
            front += 1
        else:
            break

    for i in range(len(s)-1, 1, -1):
        if s[i] == s[i-1]:
            back -= 1
        else:
            break
    
    s_front = s[:front+1]
    s_back = s[back:]
    s_middle = s[front+1:back]

    new_s = s_middle + s_back + s_front
            
    ans = 0
    cnt = 1
    for i in range(len(new_s)-1):
        if new_s[i] == new_s[i+1]:
            cnt += 1
        else:
            ans += cnt//2
            cnt = 1
    ans += cnt//2
    ans *= K-1

    cnt = 1
    for i in range(len(s_middle)-1):
        if s_middle[i] == s_middle[i+1]:
            cnt += 1
        else:
            ans += cnt//2
            cnt = 1
    ans += cnt//2
    ans += (front+1)//2 + (len(s)-back)//2
    print(ans)
    
else:
    ans = 0
    cnt = 1
    for i in range(len(s)-1):
        if s[i] == s[i+1]:
            cnt += 1
        else:
            ans += cnt//2
            cnt = 1
    ans += cnt//2
    ans *= K
    print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
    s = input()
    k = int(input())

    lens = len(s)
    if len(s) == 1:
        print(k // 2)
        sys.exit()

    if k == 1:
        r2 = 0
        rt = 1
        c = ""
        flag = False
        for se in s:
            if c == se:
                flag = True
                rt += 1
            else:
                c = se
                if flag:
                    r2 += rt // 2
                    rt = 1
                    flag = False
        r2 += rt // 2
        print(r2)
        sys.exit()

    s_daburi = 0
    s_last = s[-1]
    while s_daburi < lens:
        if s[s_daburi] == s_last:
            s_daburi += 1
        else:
            break
    s1 = s + s_last * s_daburi

    r2 = 0
    rt = 1
    c = ""
    flag = False
    for se in s1:
        if c == se:
            flag = True
            rt += 1
        else:
            c = se
            if flag:
                r2 += rt // 2
                rt = 1
                flag = False
    r2 += rt // 2

    if s_daburi == lens:
        if k % 2 == 0:
            r = r2 * (k // 2)
            print(r)
            sys.exit()
        else:
            r = r2 * (k // 2) + lens//2
            print(r)
            sys.exit()

    r = r2
    s2 = s[s_daburi:] + s_last * s_daburi
    r2 = 0
    rt = 1
    c = ""
    flag = False
    for se in s2:
        if c == se:
            flag = True
            rt += 1
        else:
            c = se
            if flag:
                r2 += rt // 2
                rt = 1
                flag = False
    r2 += rt // 2

    s3 = s[s_daburi:]
    r3 = 0
    rt = 1
    c = ""
    flag = False
    for se in s3:
        if c == se:
            flag = True
            rt += 1
        else:
            c = se
            if flag:
                r3 += rt // 2
                rt = 1
                flag = False
    r3 += rt // 2
    if k == 2:
        print(r + r3)
    else:
        print(r + r3 + r2 * (k-2))



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

# from numba import njit

# input = stdin.readline

def countProcedure(string):
  res = 0
  strCount = 1
  prev = "" # 1つまえの文字
  for i in range(len(string)):
    if string[i] == prev:
      strCount += 1
    else:
      res += strCount // 2
      strCount = 1
    prev = string[i]

  if strCount != 1:
    res += strCount // 2
  return res

def solve(s,k):
  if s[0] != s[-1]:
    return countProcedure(s)*k
  if all(x == s[0] for x in s):
    return len(s)*k//2
  else:
    leftLength = max(i for i in range(1,len(s)) if s[:i]== s[0]*i)
    left = s[0]*leftLength
    right = s[leftLength:]
    ans = countProcedure(left) + countProcedure(right) + countProcedure("".join([right,left]))*(k-1)
    return ans


def main():
  S = input()
  K = int(input())
  # N,M = map(int,input().split())
  # a = list(map(int,input().split()))
  print(solve(S,K))
  
  
if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import sys
s = input()
k = int(input())
n = len(s)
all_same = True
for i in range(n-1):
    if s[i] != s[i+1]:
        all_same = False
if all_same:
    print((n*k)//2)
    sys.exit()
head_same = 1
for i in range(n-1):
    if s[i] == s[i+1]:
        head_same += 1
    else:
        break
tail_same = 1
for i in range(n-1,0,-1):
    if s[i] == s[i-1]:
        tail_same += 1
    else:
        break
head_tail_same = 0
if s[0] == s[-1]:
    head_tail_same = head_same + tail_same
def return_internal_same(ls):
    i = 0
    same_count = 1
    return_value = 0
    while i < len(ls)-1:
        if ls[i] != ls[i+1]:
            i += 1
            return_value += same_count // 2
            same_count = 1
            continue
        else:
            same_count += 1
            i += 1
    return_value += same_count // 2
    return return_value
# head_tial_sameがあるかどうかで場合わけ
if head_tail_same > 0:
    ans = head_same//2 + tail_same//2
    ans += (k-1) * (head_tail_same//2)
    ans += k*(return_internal_same(s[head_same:n-tail_same]))
else:
    ans = k*(head_same//2 + tail_same//2)
    ans += (k-1) * (head_tail_same//2)
    ans += k*(return_internal_same(s[head_same:n-tail_same]))
print(ans)