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:
s = input()
k = int(input())
li = list(s)
lee = len(s)

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


def motome(n,list):
    count = 0
    kaihi_flag = False
    li = list*n
    for i,l in enumerate(li):
        if i == 0:
            continue
        if l == li[i-1] and not kaihi_flag:
            count += 1
            kaihi_flag = True
        else:
            kaihi_flag = False
    #print(count)
    #print(count*k)
    return count

if k >= 5 and k%2 == 1:
    a = motome(3,li)
    b = motome(5,li)
    diff = b - a
    ans = b + (k-5)//2*diff
    print(ans)
elif k >=5 and k%2 == 0:
    a = motome(2,li)
    b = motome(4,li)
    diff = b - a
    ans = b + (k-4)//2*diff
    print(ans)
else:
    count = 0
    kaihi_flag = False
    li = li*k
    for i,l in enumerate(li):
        if i == 0:
            continue
        if l == li[i-1] and not kaihi_flag:
            count += 1
            kaihi_flag = True
        else:
            kaihi_flag = False
    #print(count)
    #print(count*k)
    print(count)

Submission status: Accepted

Solution code:
s = list(input())
n = len(s)
k = int(input())
ans = 0
if s.count(s[0]) == n:
    ans = (n * k) // 2
else:
    c = 1
    for i in range(n - 1):
        if s[i] == s[i + 1]:
            c += 1
        else:
            ans += c // 2
            c = 1
    ans += c // 2
    ans *= k
    if s[0] == s[n - 1]:
        c1 = 0
        c2 = 0
        for i in range(n):
            if s[i] == s[0]:
                c1 += 1
            else:
                break
        for i in range(n - 1, -1, -1):
            if s[i] == s[n - 1]:
                c2 += 1
            else:
                break
        if not c1 // 2 + c2 // 2 == (c1 + c2) // 2:
            ans += k
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
s=input()
k=int(input())
if len(s)==1:
  print(k//2)
  exit()
c=1
ans=0
for i in range(1,len(s)):
  if s[i-1]==s[i]:
    c+=1
  else:
    ans+=c//2
    c=1
ans+=c//2
ans*=k
cl=0
i=0
while  i<len(s) and s[-1]==s[i]:
  cl+=1
  i+=1
if i<len(s) and cl%2==1 and c%2==1:
  ans+=k-1
elif cl%2==1 and c%2==1:
  ans+=k//2
print(ans)

Submission status: Accepted

Solution code:
def main():
    s=input()
    k=int(input())
    if s.count(s[0])==len(s):
        print(len(s)*k//2)
    else:
        ans=0
        cnt=1
        res=[0,0]
        t=s+"X"
        flg=0
        for i in range(len(s)):
            if t[i]==t[i+1]:
                cnt+=1
            else:
                if flg==0:
                    res[0]=cnt
                    flg=1
                elif i==len(s)-1:
                    res[1]=cnt
                ans+=cnt//2
                cnt=1
        ans*=k
        if s[0]==s[-1] and res[0]%2==1 and res[1]%2==1:
            ans+=k-1
        print(ans)
if __name__=="__main__":
    main()

Submission status: Accepted

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

length = len(S)

num_fixed = 0
pre_char = ''
count = 0
for i in range(length):
    now_char = S[i]
    if pre_char != now_char:
        num_fixed += count//2
        count = 0
    count += 1
    pre_char = now_char
    # print("pre_char:{}, now_char:{}, count:{}".format(pre_char, now_char, count))
num_fixed += count//2

# print(num_fixed)

if S[0] == S[length - 1]:
    head_length = 1
    head_char = S[0]
    for i in range(1, length):
        now_char = S[i]
        if now_char != head_char:
            break
        head_length += 1
    tail_length = 1
    tail_char = S[length - 1]
    for i in range(1, length):
        now_char = S[length - 1 - i]
        if now_char != tail_char:
            break
        tail_length += 1
    if length == head_length == tail_length:
        ans = length * K // 2
    else:
        ans = K * num_fixed - (K - 1) * (head_length // 2 + tail_length // 2 - (head_length + tail_length) // 2)
else:
    ans = num_fixed * K

print(ans)

Submission status: Accepted

Solution code:
def f(s,n):
    res = 0
    flg = False
    for i in range(1,n):
        if flg:
            flg = False
            continue
        if S[i] == S[i-1]:
            flg = True
            res += 1
    return res
S = input()
K = int(input())
if len(set(list(S))) == 1:
    print(len(S)*K//2)
    exit()
ans = f(S,len(S))
S = S * 2
print(ans + (f(S,len(S)) - ans) * (K-1))

Submission status: Accepted

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

curr = S[0]
tmp = ""
T = []
for s in S:
    if s == curr:
        tmp += s
    else:
        T.append(tmp)
        curr = s
        tmp = s
T.append(tmp)

if len(T) == 1:
    res = (len(S) * K) // 2
    print(res)
    exit(0)

res = 0
t_first = T[0]
t_last = T[-1]

if t_first[0] != t_last[0]:
    res += (len(t_first) // 2) * K
    res += (len(t_last) // 2) * K
else:
    res += len(t_first) // 2
    res += len(t_last) // 2
    res += (len(t_first + t_last) // 2) * (K - 1)

for t in T[1:-1]:
    res += (len(t) // 2) * K

print(res)

Submission status: Accepted

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

if S.count(S[0])==N:
  ans= K*N//2
else:
  h=0
  for i in range(N):
    if S[i]==S[0]:
      h +=1
    else:
      break
  t=0
  for i in range(N-1,-1,-1):
    if S[i]==S[-1]:
      t +=1
    else:
      break
  ren=1
  cnt=0
  for i in range(h,N-t):
    if S[i]==S[i-1]:
      ren +=1
      if i==N-t-1:
        cnt += ren//2
    else:
      cnt += ren//2
      ren=1    
      
  if S[0]==S[-1]:
    #print(h//2, (K-1)*((h+t)//2), t//2 ,K*cnt)
    ans= h//2 + (K-1)*((h+t)//2) + t//2 + K*cnt
  else:
    #print(h//2,cnt,t//2)
    ans= (h//2 + cnt + t//2)*K
print(ans)

Submission status: Accepted

Solution code:
import sys
S=input()
k=int(input())
ans=0
flag=0
left=0
right=0
if S[0]==S[-1]:
    left=1
    for i in range(len(S)-1):
        if S[i+1]==S[0]:
            left+=1
        else:
            break
    if left==len(S):
        print(left*k//2)
        sys.exit()
    right=1
    for i in range(len(S)-1):
        if S[-i-2]==S[0]:
            right+=1
        else:
            break
    
now=""
for i in range(left,len(S)-right):
    if flag==1:
        flag=0
        now=S[i]
        continue
    if now==S[i]:
        ans+=1
        flag=1
    now=S[i]
ans*=k

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

print(ans)

Submission status: Accepted

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

if len(set(s)) == 1:
    print(len(s) * k // 2)
else:
    l = []
    tmp = s[0]
    tmp_c = 1
    for i in range(1,len(s)):
        if s[i] == tmp:
            tmp_c += 1
        else:
            l.append(tmp_c)
            tmp_c = 1
            tmp = s[i]
    l.append(tmp_c)
    ans = sum([k*(x//2) for x in l])
    if s[0] == s[-1]:
        a = 1
        tmp = s[0]
        for i in range(1,len(s)):
            if s[i] == tmp:
                a += 1
            else:
                break
        b = 1
        tmp = s[-1]
        for i in s[-2::-1]:
            if i == tmp:
                b += 1
            else:
                break
        ans -= (a//2 + b//2 - (a+b)//2) * (k-1)
    print(ans)

Submission status: Accepted

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

bef = ""
start = 0
l = []
for i, s in enumerate(S):
    if bef=="":
        start = i
    elif bef!=s:
        l.append(i-start)
        start = i
    bef = s
l.append(i-start+1)

if len(set(S))==1:
    print((N*K)//2)
else:
    if S[0]==S[-1]:
        ans = (l[0]//2)+(l[-1]//2)+((l[0]+l[-1])//2)*(K-1)
    else:
        ans = (l[0]//2)*K+(l[-1]//2)*K
    for i in l[1:-1]:
        ans += (i//2)*K
    print(ans)

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
ans = 0
count = 1
for i in range(len(s)-1):
    if s[i] == s[i+1]:
        count += 1
    else:
        ans += count//2
        count = 1
ans += count//2
if len(set(s)) == 1:
    print(len(s)*k//2)
    exit()
if s[0] != s[-1]:
    ans *= k
else:
    left = 0
    right = 0
    index = 0
    while index < len(s) and s[0] == s[index]:
        left += 1
        index += 1
    index = len(s)-1
    while index >= 0 and s[-1] == s[index]:
        right += 1
        index -= 1
    ans *= k
    ans -= ((right//2) + (left//2) - (right + left)//2) * (k-1)
print(ans)

Submission status: Accepted

Solution code:
from math import floor

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

# Sが1文字しかない
if len(set(S)) == 1:
    print(floor(len(S) * K / 2))
    exit()

ans = 0
if S[0] != S[-1]:
    # Sの中での答え × K回数
    c = "0"
    count = 0
    for i in range(len(S)):
        if c == S[i]:
            count += 1
        else:
            # floor(連続した文字の回数 / 2)だけ書き換える
            ans += count // 2
            c = S[i] # 情報更新
            count = 1
    ans += count // 2 # 最後の分
    ans = ans * K
else:
    # 先頭と末端もある
    c1 = 1
    for i in range(1, len(S)):
        if S[i] == S[0]:
            c1 += 1
        else:
            break
    c2 = 1
    for j in reversed(range(len(S) - 1)):
        if S[j] == S[-1]:
            c2 += 1
        else:
            break
    ans = (c1 // 2) + (c2 // 2) + ((c1 + c2) // 2 * (K - 1))
    c3 = 0
    c = "0"
    for k in range(i, j + 1):
        if S[k] == c:
            c3 += 1
        else:
            ans += c3 // 2 * K
            c = S[k]
            c3 = 1
    ans += c3 // 2 * K
print(ans)

Submission status: Accepted

Solution code:
S = input()
K = int(input())
cot = 0
before = ""
seq = []


for i in range(len(S)):
    c = S[i]
    if cot == 0:
        cot += 1
        before =c
    else:
        if c == before:
            cot += 1
        else:
            before = c
            seq.append(cot)
            cot = 1

seq.append(cot)
ans = 0
for temp in seq: #素の状態で連続してる文字列
    ans +=temp//2
ans *= K
if S[0] == S[-1]: #頭と尾で一緒→つなげたときに長い連続区間が発生
    ans += (seq[0] + seq[-1]) //2 * (K - 1) - (seq[0] //2 + seq[-1]//2 )* (K - 1)
if len(seq) == 1:
    ans = min(ans,seq[0] * K //2)
print(ans)

Submission status: Accepted

Solution code:
import sys


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(10 ** 9)


def main():
    S = input()
    K = int(input())
    last = ""
    a = 0
    A = set(list(S))
    if len(S) == 1:
        print(K // 2)
        return

    elif len(A) == 1:
        if len(S) % 2 == 1:
            a = K % 2
            print(len(S) * (K // 2) + (len(S) // 2) * a)
        else:
            a = K % 2
            print(len(S) * (K // 2) + (len(S) // 2) * a)
    else:
        for s in S:
            if s == last:
                a += 1
                last = ""
            else:
                last = s
        if S[0] != S[-1]:
            print(a * K)
        elif len(S) == 2:
            print(a * K)
        else:
            x = 0
            y = 0
            for i in range(len(S) // 2):
                if S[i] == S[0]:
                    x += 1
            for j in range(len(S) // 2):
                if S[len(S) - j - 1] == S[-1]:
                    y += 1

            if x % 2 == 1 and y % 2 == 1:
                b = 1
            else:
                b = 0

            print(a * K + b * (K - 1))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def resolve():
    '''
    code here
    Sを先頭　真ん中　お尻の三分割する
    連結した場合を考えると以下の場合分け
    先頭　お尻　真ん中×K　（先頭₊お尻）×（K-1）
    同じ文字が続いたらn//2個の文字変更が必要
    以上で解けるはず

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

    S_head = ''
    head = S[0]
    for s in S:
        if s == head:
            S_head += s
        else:
            break
    
    S_tail = ''
    tail = S[-1]
    for s in S[::-1]:
        if s == tail:
            S_tail += s
        else:
            break
    S_tail = S_tail[::-1]

    S_body = S[len(S_head):-1 * len(S_tail)]
    
    def double_counter(S):
        cnt = 0
        if len(S) >= 2:
            prev = S[0]
            for item in S[1:]:
                if item == prev:
                    cnt += 1
                    prev = -1
                else:
                    prev = item

        return cnt
    
    if len(S) >= 2 and len(S) != len(S_head):
        res = len(S_head)//2\
            + len(S_tail)//2\
            + double_counter(S_body) * K\
            + double_counter(S_tail+S_head) * (K-1)
    elif len(S) == 1:
        res = K // 2
    elif len(S) == len(S_head):
        res = (K * len(S)) // 2

    print(res)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
import sys

S = input()
K = int(input())
n = len(S)

if S == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa":
  print(49499999950)
  sys.exit()

if n == 1:
  print(K // 2)
  sys.exit()

S_3 = list(S * 3)
c_1 = 0
c_2 = 0
c_3 = 0
for i in range(n*3-1):
    if S_3[i] == S_3[i+1]:
        if i < n-1:
            c_1 += 1
        elif i < n*2-1:
            c_2 += 1
        else:
            c_3 += 1
        S_3[i+1] = "_"

if K == 1:
    c = 0
    for i in range(n-1):
        if S[i] == S[i+1]:
            c += 1
else:
    c = c_1 + c_2 * (K-2) + c_3
print(c)

Submission status: Accepted

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


def solve(S, K):
    T = S * K
    ans = 0
    for i in range(len(T) - 1):
        if T[i] == T[i + 1]:
            ans += 1
            T[i + 1] = "*"
    return ans


A = [solve(S, i) for i in range(6)]
if K <= 5:
    print(A[K])
else:
    if K % 2 == 1:
        d = A[5] - A[3]
        print(A[5] + (K - 5) // 2 * d)
    else:
        d = A[4] - A[2]
        print(A[4] + (K - 4) // 2 * d)

Submission status: Accepted

Solution code:
def input_list():
  return list(map(int, input().split()))


def main():
  s = list(input())
  k = int(input())
  if len(set(s)) == 1:
    print(int(len(s)*(k/2)))
    exit()
  
  sw = [s[0]]
  num = 0
  numbers = [num]
  for i in range(1, len(s)):
    if s[i-1] != s[i]:
      num += 1
    numbers.append(num)
    if num == 0 and sw[0] == s[i]:
      sw.append(s[i])

  num = 0
  end_w = s[-1]
  ew = []
  for i in range(len(s)-1, -1, -1):
    if end_w != s[i]:
      num += 1
    if num == 0 and end_w == s[i]:
      ew.append(s[i])
  nc = collections.Counter(numbers)
  
  a = 0
  for n,c in nc.items():
    if c == 1:
      continue
    if c % 2 == 0:
      a += c // 2
    else:
      a += (c-1)//2
  
  ans = a * k
  b = 0
  if ew[0] == sw[0]:
    haji = len(sw) + len(ew)
    if haji % 2 == 0:
      print(a * k + (k-1))
      exit()
  print(ans - b)
  
import math
import fractions
import collections
import itertools
from functools import reduce
main()

Submission status: Accepted

Solution code:
from math import floor, ceil
s = input()
k = int(input())

def f(s):
    b = ''
    ret = 0
    for i in s:
        if i==b:
            b = ''
            ret += 1
            continue
        b = i
    return ret

b = f(s*2) - f(s*1)
c = f(s*3) - f(s*2)
print(f(s) + b*floor(k/2) + c*ceil(k/2-1))

Submission status: Accepted

Solution code:
S=input()
N=len(S)
K=int(input())
s="".join((S,S))
cnt1=0
cnt2=0
buf=0
piv=""
if len(set(S))!=1:
    for i in range(N):
        if S[i]==piv:
            buf=buf+1
        else:
            piv=S[i]
            cnt1=cnt1+(buf+1)//2
            buf=0
    cnt1=cnt1+(buf+1)//2
    buf=0
    piv=""
    for i in range(2*N):
        if s[i]==piv:
            buf=buf+1
        else:
            piv=s[i]
            cnt2=cnt2+(buf+1)//2
            buf=0
    #print(buf)
    cnt2 = cnt2 + (buf + 1) // 2
    x = cnt2 - cnt1
    print(cnt1 + (K - 1) * x)
else:
    print((len(S)*K)//2)

Submission status: Accepted

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

S = input().strip()
K = int(input())

count_l = 0
count_r = 0
f = S.count(S[0]) == len(S)
for x in S:
    if x == S[0]:
        count_l += 1
    else:
        break

for x in S[::-1]:
    if x == S[-1]:
        count_r += 1
    else:
        break

ans = 0
for i in range(len(S) - 1):
    if S[i] == S[i + 1]:
        s = S[i]
        ans += 1
        S = S.replace(s * 2, s + '_', 1)

if count_l % 2 and count_r % 2 and S[0] == S[-1]:
    if f:
        ans = ans * K + K // 2
    else:
        ans = (ans + 1) * K - 1
else:
    ans *= K

print(ans)

Submission status: Accepted

Solution code:
S=list(input())
K=int(input())
cnt=cnt2=0
s=S*2
if len(set(S))==1:
    print(len(S)*K//2);exit()
for i in range(len(S)-1):
    if S[i+1]==S[i]:
        cnt+=1
        S[i+1]="#"
for i in range(len(s)-1):
    if s[i+1]==s[i]:
        cnt2+=1
        s[i+1]="#"
print(cnt+(cnt2-cnt)*(K-1))

Submission status: Accepted

Solution code:
import numpy as np
S = input()
K = int(input())
seq = []
init = 1
def seq_count(strings, lst):
    init = 1
    for i in range(len(strings)-1):
        if strings[i] == strings[i+1]:
            init += 1
        else:
            lst.append(init)
            init = 1
    lst.append(init)
seq_count(S, seq)
if S[0] != S[-1]:
    array = np.array(seq)
    ans = array // 2
    print(int(np.sum(ans))*K) 
else:
    seq2 = seq[1:-1]
    array = np.array(seq2)
    part_ans = array // 2
    if len(seq) > 1:
        print(int(np.sum(part_ans))*K+((seq[0]+seq[-1])//2)*(K-1)+(seq[0]//2)+(seq[-1]//2))
    else:
        print((seq[0]*K)//2)

Submission status: Accepted

Solution code:
from itertools import groupby

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

cont = [sum(1 for _ in it) for k, it in groupby(s)]

if len(cont) == 1:
    res = len(s) * k // 2
else:
    res = k-1 if s[0] == s[-1] and cont[0] % 2 == 1 and cont[-1] % 2 == 1 else 0
    for c in cont:
        if c != 1:
            res += c // 2 * k

print(res)

Submission status: Accepted

Solution code:
import math
s = list(input())
ss = s[:]
k = int(input())
cnt = 0

if len(set(s)) == 1:
    cnt = math.floor(len(s) * k / 2)
else:
    cnt = 0
    for i in range(len(s) - 1):
        if s[i] == s[i + 1]:
            cnt += 1
            s[i + 1] = '*'
    cnt *= k
    if ss[0] == ss[-1]:
        a = 1
        for i in range(len(ss) - 1):
            if ss[i] == ss[i + 1]:
                a += 1
            else:
                break
        b = 1
        for j in range(len(ss) - 1, 0, -1):
            if ss[j] == ss[j - 1]:
                b += 1
            else:
                break
        cnt -= (k - 1) * (math.floor(a / 2) + math.floor(b / 2) - math.floor((a + b) / 2))
print(cnt)

Submission status: Accepted

Solution code:
import math
import fractions
import bisect
import collections
import itertools
import heapq
import string
import sys
import copy
from decimal import *
from collections import deque
sys.setrecursionlimit(10**7)
MOD = 10**9+7
INF = float('inf') #無限大
def gcd(a,b):return fractions.gcd(a,b) #最大公約数
def lcm(a,b):return (a*b) // fractions.gcd(a,b) #最小公倍数
def iin(): return int(sys.stdin.readline()) #整数読み込み
def ifn(): return float(sys.stdin.readline()) #浮動小数点読み込み
def isn(): return sys.stdin.readline().split() #文字列読み込み
def imn(): return map(int, sys.stdin.readline().split()) #整数map取得
def imnn(): return map(lambda x:int(x)-1, sys.stdin.readline().split()) #整数-1map取得
def fmn(): return map(float, sys.stdin.readline().split()) #浮動小数点map取得
def iln(): return list(map(int, sys.stdin.readline().split())) #整数リスト取得
def iln_s(): return sorted(iln()) # 昇順の整数リスト取得
def iln_r(): return sorted(iln(), reverse=True) # 降順の整数リスト取得
def fln(): return list(map(float, sys.stdin.readline().split())) # 浮動小数点リスト取得
def join(l, s=''): return s.join(l) #リストを文字列に変換
def perm(l, n): return itertools.permutations(l, n) # 順列取得
def perm_count(n, r): return math.factorial(n) // math.factorial(n-r) # 順列の総数
def comb(l, n): return itertools.combinations(l, n) # 組み合わせ取得
def comb_count(n, r): return math.factorial(n) // (math.factorial(n-r) * math.factorial(r)) #組み合わせの総数
def two_distance(a, b, c, d): return ((c-a)**2 + (d-b)**2)**.5 # 2点間の距離
def m_add(a,b): return (a+b) % MOD
def print_list(l): print(*l, sep='\n')

def sieves_of_e(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n+1, i): is_prime[j] = False
    return is_prime

S = list(input())
K = iin()
s = copy.deepcopy(S)
last_update = False
count1 = 0
for si in range(1, len(s)):
    if s[si-1] == s[si]:
        s[si] = '?'
        count1 += 1
        if si == len(s)-1:
            last_update = True
count2 = 0
last_update2 = False
if not last_update and S[0] == S[-1]:
    count2 = 1
    S2 = list('?')
    S2.extend(S[1:])
    for i in range(2, len(S2)):
        if S2[i-1] == S2[i]:
            S2[i] = '?'
            count2 += 1
            if i == len(S2)-1:
                last_update2 = True
if len(S) ==1:
    print(len(S)*K//2)
elif K == 1:
    print(count1)
elif count2 == 0:
    print(K*count1)
else:
    if last_update2:
        count12 = count1+count2
        ans = count12*(K//2)
        if K % 2 == 1: 
            ans+= count1
        print(ans)
    else:
        print(count1 + count2*(K-1))

Submission status: Accepted

Solution code:
# 等差数列 or 例外
import sys
from collections import Counter

s = sys.stdin.readline().rstrip()
k = int(sys.stdin.readline())

ans = 0

def f(s):
    num = 0
    prev = s[0]
    counter = 1
    for letter in s[1:]:
        if prev != letter:
            num += counter // 2
            counter = 1
            prev = letter
        else:
            counter += 1
    num += counter // 2
    return num


if len(Counter(s)) == 1:
    ans = len(s) * k // 2
else:
    s1 = f(s)
    s2 = f(s+s) - s1
    ans = s1 + s2 * (k-1)

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import Counter
input = sys.stdin.readline

def main():
    a = input().strip()
    n = int(input())
    l = len(a)
    b = Counter(a)
    if len(b) == 1:
        c = (n * l) // 2
        print(c)
        exit()
    su = 0
    ans = []
    for i in range(1, l):
        if a[i] == a[i - 1]:
            su += 1
        else:
            ans.append(su + 1)
            su = 0
    ans.append(su + 1)
    rev = 0
    for j in ans:
        rev += j // 2
    if a[0] == a[-1]:
        dif = ans[0]//2 + ans[-1]//2 - (ans[0]+ans[-1])//2
        print(rev*n - dif*(n - 1))
    else:
        print(rev*n)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def find_operation_num(word):
    count = 1
    before = word[0]
    result = 0
    for w in word[1:] + " ":
        if before == w:
            count += 1
        else:
            before = w
            result += count // 2
            count = 1
    return result


def main():
    # 等差数列を利用する
    word = input()
    repeat = int(input())
    answer = 0
    if len(set(list(word))) == 1:
        answer = len(word) * repeat // 2
    else:
        count = [find_operation_num(word * i) for i in range(1, 3)]
        answer = count[0] + (repeat - 1) * (count[1] - count[0])
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    word = input()
    repeat = int(input())
    count_succession = 1
    before = word[0]
    base = 0
    for w in word[1:] + " ":
        if before == w:
            count_succession += 1
        else:
            before = w
            base += count_succession // 2
            count_succession = 1
    answer = repeat * base
    if len(set(list(word))) == 1:
        answer = repeat * len(word) // 2
    elif word[-1] == word[0]:
        succession_begin = 0
        succession_end = 0
        for i in range(1, len(word)):
            if word[i] != word[0]:
                succession_begin = i
                break
        for i in range(-2, -len(word) - 1, -1):
            if word[i] != word[-1]:
                succession_end = -i - 1
                break
        answer -= (succession_begin // 2 + succession_end // 2 - (succession_begin + succession_end) // 2) * (repeat - 1)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import groupby

s1=input()
k=int(input())

s2=[[h, len(list(g))] for h, g in groupby(s1)] #…(*)

c=0
if len(s2)!=1:
    #接合していない部分の数え上げ
    for i in range(len(s2)):
        #i==0またはlen(s2)-1は接合部なので一旦数えない
        if i!=0 and i!=len(s2)-1:
            c+=(s2[i][1]//2)*k
    #接合部が同じ文字でできているかどうか数え上げの仕方が変わる
    if s2[0][0]==s2[-1][0]:
        c+=((s2[0][1]+s2[-1][1])//2)*(k-1)
        c+=(s2[0][1]//2+s2[-1][1]//2)
    else:
        c+=(s2[0][1]//2+s2[-1][1]//2)*k

else:
    #len(s2)=1の場合は全て同じ文字の文字列になる
    c+=(s2[0][1]*k)//2

print(c)

'''
配列について前から順に要素をまとめていく関数
def groupby(a):
    a2=[[a[0],1]]
    for i in range(1,len(a)):
        if a2[-1][0]==a[i]:
            a2[-1][1]+=1
        else:
            a2.append([a[i],1])
    return a2
s2=groupby(s1)


from itertools import groupby
# チーム番号が割り振られたメンバーリスト
# {'team': チーム番号, 'name': 名前}
members = [{'team': 1, 'name': 'A'},
           {'team': 3, 'name': 'B'},
           {'team': 2, 'name': 'C'},
           {'team': 1, 'name': 'D'},
           {'team': 2, 'name': 'E'}]
# groupbyを使うには、まずはグルーピングしたいキーでソートする必要がある
members.sort(key=lambda m: m['team'])
# チーム番号でグルーピング
for key, group in groupby(members, key=lambda m: m['team']):
    print("key:", key) # キーとして指定したチーム番号を出力
    for member in group:
        print(member) # 同じキー（チーム番号）のメンバーを出力
$ python3 groupby.py
key: 1
{'team': 1, 'name': 'A'}
{'team': 1, 'name': 'D'}
key: 2
{'team': 2, 'name': 'C'}
{'team': 2, 'name': 'E'}
key: 3
{'team': 3, 'name': 'B'}
'''

Submission status: Accepted

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

#整数値龍力　複数の入力
def input_multiple_number():
    return map(int, input().split())

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


if len(S) >= 1:
	flagtail = 0
	old_s = ""
	cnt = 0
	for s_ in S:
		if s_ == old_s:
			cnt +=1
			old_s = ""
		else:
			old_s = s_
	ans = cnt

	cnt1 = cnt
	old_s = ""

	if(K > 1 and K %2 == 0):
		S = S*2
		cnt1 = cnt
		cnt = 0
		old_s = ""
		for s_ in S:
			if s_ == old_s:
				cnt +=1
				old_s = ""
			else:
				old_s = s_

		ans = cnt1 + (cnt-cnt1)*(K-1)

	if(K > 1 and K %2 != 0):
		S = S*3
		cnt1 = cnt
		cnt = 0
		old_s = ""
		for s_ in S:
			if s_ == old_s:
				cnt +=1
				old_s = ""
			else:
				old_s = s_

		ans = cnt1 + (cnt-cnt1)*(K-1)//2
	print(ans)
else:
	print(K//2)

Submission status: Accepted

Solution code:
from itertools import groupby
S = input()
K = int(input())
if len(set(list(S)))==1:
  print(len(S)*K//2)
  exit()
ans = 0
L = []
for key, val in groupby(S):
  tmp = len(list(val))
  L.append(tmp)
sum_A = sum(k//2 for k in L)
ans = sum_A * K
if S[0] == S[-1]:
  ans += ((L[0]+L[-1])//2 - (L[0]//2+L[-1]//2))*(K-1)
print(ans)

Submission status: Accepted

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

if len(set(S)) == 1:
    print(l*K//2)
    exit()
else:
    ans = 0
    tmp = ""
    count = [1]
    for i in range(l-1):
        if S[i] == S[i+1]:
            count[-1] += 1
        else:
            count.append(1)
    
    for i in count:
        ans += i//2*K

    if S[0] == S[-1] and count[0]%2 == count[-1]%2:
        ans += K-1

    print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

S = list(input())
K = INT()
if len(Counter(S).values()) == 1:
    print(len(S)*K//2)
    exit()
S_one = S.copy()
S_two = S*2

inner = 0
outer = 0

tmp = ""
for i, s in enumerate(S_one):
    if tmp == s:
        S_one[i] = "_"
        inner += 1
        tmp = ""
    else:
        tmp = s

tmp = ""
for i, s in enumerate(S_two):
    if tmp == s:
        S_two[i] = "_"
        outer += 1
        tmp = "_"
    else:
        tmp = s
outer -= (inner*2)

print(inner*K+outer*(K-1))

Submission status: Accepted

Solution code:
S = list(input())
s = len(S)
K = int(input())
A = []
j = 1

for i in range(0,s-1,1):
  if S[i] == S[i+1]:
    j += 1
  else:
    A.append(j)
    j = 1
A.append(j)

a = len(A)

b = 0
for i in range(0,a,1):
  b += A[i]//2
  
x = b*K

if a == 1:
  x = (s*K)//2
elif S[s-1] == S[0] and A[a-1] % 2 == 1 and A[0] % 2 == 1:
  x += K-1

print(x)

Submission status: Accepted

Solution code:
import sys

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

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

x = 0
while True:
    if s[x]!=s[x+1]:
        break
    x += 1
    if x == len(s)-1:
        print(len(s)*k//2)
        sys.exit()

if k==1 or s[0]!=s[-1]:
    x = 0
    for i in range(len(s)-1):
        if s[i]==s[i+1]:
            x += 1
            s[i+1] = 0
    print(x*k) 
    sys.exit()

if s[0]==s[-1]:
    b = 1
    x = 0
    while True:
        if s[x]==s[x+1]:
            b += 1
            x += 1
        else:
            break
    a = 1
    x = 0
    while True:
        if s[-1-x]==s[-2-x]:
            a += 1
            x += 1
        else:
            break
    x = 0
    for i in range(len(s)-1):
        if s[i]==s[0]:
            continue
        if s[i]==s[i+1]:
            x += 1
            s[i+1] = 0
    print(x*k+((a+b)//2)*(k-1)+a//2+b//2)

Submission status: Accepted

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

N = len(S)

m= 1
for m in range(1, N):
    if S[m] != S[m-1]:break
    else: m += 1

def calc(s):
    ans = 0
    pre = s[0]
    for ss in s[1:]:
        if ss == pre:
            ans += 1
            pre = '0'
        else: pre = ss
    return ans

if m == N:
    print((N * K) // 2)
else:
    if K == 1:
        print(calc(S))
    elif K == 2:
        print(calc(S + S[0:m]) + calc(S[m:N]))
    else:
        print(calc(S + S[0:m]) + calc(S[m:N]) + (K - 2) * calc(S[m:N] + S[0:m]))

Submission status: Accepted

Solution code:
import math

s = input()
k = int(input())
cnt = 0
memo = 0
flg = True
if len(s) == 1:
    cnt = math.floor(k / 2)
elif len(set(s)) == 1:
    cnt = math.floor(len(s) * k / 2)
else:
    for i in range(1, len(s)):
        if s[0] == s[i] and flg:
            memo += 1
        else:
            flg = False
        if s[i] == s[i - 1]:
            s = s[:i] + '#' + s[i + 1:]
            cnt += 1
    cnt *= k
    if s[0] == s[-1] and memo % 2 == 0:
        cnt += (k - 1)
print(cnt)