AGC039 A - Connection and Disconnection

備忘録

問題

atcoder.jp

回答

import sys
import os
import math
import bisect
import itertools
import collections
import heapq
import queue
import array
import time

# 時々使う
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

# 再帰の制限設定
sys.setrecursionlimit(10000000)


def ii(): return int(sys.stdin.buffer.readline().rstrip())
def il(): return list(map(int, sys.stdin.buffer.readline().split()))
def fl(): return list(map(float, sys.stdin.buffer.readline().split()))
def iln(n): return [int(sys.stdin.buffer.readline().rstrip())
                    for _ in range(n)]


def iss(): return sys.stdin.buffer.readline().decode().rstrip()
def sl(): return list(map(str, sys.stdin.buffer.readline().decode().split()))
def isn(n): return [sys.stdin.buffer.readline().decode().rstrip()
                    for _ in range(n)]


def lcm(x, y): return (x * y) // math.gcd(x, y)


MOD = 10 ** 9 + 7
INF = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    S = iss()
    K = ii()
    N = len(S)
    if N == 1 or len(set(S)) == 1:
        # 文字数1または全て同じ文字
        print(int(N * (K / 2)))
        exit()

    ret = 0
    S = list(S)
    for i in range(1, N):
        if S[i] == S[i-1]:
            ret += 1
            S[i] = '1'

    if S[0] != S[-1]:
        print(ret * K)
    else:
        # 先頭と末尾の文字が同じ場合、
        # 同じ文字が何度連続で出現しているかカウントする
        cnt = bisect.bisect(S, S[0]) + bisect.bisect(S[::-1], S[0])
        if cnt % 2 == 0:
            print(ret * K + (K - 1))
        else:
            print(ret * K)


if __name__ == '__main__':
    main()

考え方

愚直にケースを分けてケースごとの回答を考えます

  • 回答概要
    • 「文字数が1または全て同じ文字」「先頭と末尾が異なる文字」「先頭と末尾が同じ文字」の3ケースが存在する
    • 「先頭と末尾が同じ文字」の場合でも、文字が連続している回数でケース分けが必要

参考

[C#] AGC-039-A - Connection and Disconnection | AtriaSoft