1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[ABC456] ABC 456(Atcoder Beginner Contest)のA~C(A,B,C)問題をPythonで解説(復習)

1
Posted at

[ABC456] ABC 456(Atcoder Beginner Contest)のA~C(A,B,C)問題をPythonで解説(復習)

A問題

  • 愚直に for ループで全パターン試そうぜ
A.py
"""
<方針>
- 愚直に `for` ループで全パターン試そうぜ
"""
# 入力
X = int(input())

for i in range(1, 7):
  for j in range(1, 7):
    for k in range(1, 7):
      # 一致するかどうか
      if((i+j+k) == X):
        print("Yes")
        exit()

print("No")

B問題

  • 面倒だけど,それぞれのサイコロ A B C4 5 6 が出るパターン(3! 通り)を全部試すか...
B.py
"""
<方針>
- 面倒だけど,それぞれのサイコロ `A B C` で `4 5 6` が出るパターン(`3!` 通り)を全部試すか...
"""
from itertools import permutations

AA = [list(map(int, input().split())) for _ in range(3)]

# パターン数
cnt = 0
for X in permutations([4, 5, 6], 3):
  # 掛け算
  tmp = 1
  for A, x in zip(AA, X):
    tmp *= A.count(x)
  # 足し算
  cnt += tmp

# 確率
ans = cnt/(6**3)
print(ans)

C問題

方針

  • 同じ文字が連続する文字列の部分を切れ目として,考える.
  • 一つのまとまり(文字不連続)(長さ l )から,取れる部分文字列の個数は,1~lの総和なので,l*(l+1)//2

前提

  • C問題あたりで,TLEになる人は,制約条件を見る癖をつけよう.
  • AB問題では,基本的に制約条件を見ずにやっても解ける.
  • しかし,C問題以降では,制約条件を見ないと必ずTLEすると思っても良い.
  • 詳しい話は私の352回の記事C問題の解説に記したので,是非参照してほしい.
C.py
"""
<方針>
- 同じ文字が連続する文字列の部分を切れ目として,考える.
- 一つのまとまり(文字不連続)(長さ `l` )から,取れる部分文字列の個数は,1~lの総和なので,`l*(l+1)//2`
"""
S = list(input())
MOD = 998244353

N = len(S)

# 番兵を加える
S += S[-1]

ans = 0

# 文字不連続の長さ
l = 1

for i in range(N):
  # 文字が違うなら
  if(S[i] != S[i+1]):
    l += 1
  # 文字が同じなら
  else:
    # 1~lの総和をたす
    ans += l*(l+1)//2
    ans %= MOD
    # 長さをもとに戻す
    l = 1

print(ans)

補足

関係するリンク(参考文献など)

筆者について

その他

  • 間違いを含んでいる可能性があります.
  • 方針と言いつつ,方針ではない感想などを書いている可能性があります.
  • A問題から解説がだんだん省略されます.
  • コードに書かれている解説の文言と,その上に書いてある解説の文言を変えている場合があります.

最後に一言

  • ハンチョー
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?