AtCoder Beginner Contest 449の問題をPythonで解いてみました。
A - π
円の面積の公式は、半径×半径×円周率です。
Pythonで円周率は、math.piなどで取得できます。
main.py (A - π)
import math
print((int(input()) / 2) ** 2 * math.pi)
B - Deconstruct Chocolate
現在のチョコレートの縦と横の長さを、それぞれ取得したhとwで管理します。
main.py (B - Deconstruct Chocolate)
h, w, q = map(int, input().split())
for _ in range(q):
query_type, query_num = map(int, input().split())
if query_type == 1:
print(query_num * w)
h -= query_num
else:
print(query_num * h)
w -= query_num
C - Comfortable Distance
入力文字列sのi番目に対して、次の2つを管理していきます。
-
active[c]:現在のiに対して、$L \leq i - j \leq R$を満たす、文字cの過去インデックスj1 -
waiting[c]:現在のiに対して、$L \leq i - j \leq R$をまだ満たしていない、文字cの過去インデックスj
以下を繰り返すことで求められます。
- もう条件を満たさなくなったインデックスを、
activeから除外する。 - 新たに条件を満たすようになったインデックスを、
waitingからactiveに移動させる。 -
active[s[i]]の長さを答えに加える。 -
waiting[s[i]]にiを追加する。
activeとwaitingの要素に対しては、collections.deque() を使用すると高速です。末尾への追加や先頭の削除を頻繁に行うためです。
main.py (C - Comfortable Distance)
from collections import deque
n, l, r = map(int, input().split())
s = input()
active = [deque() for _ in range(26)]
waiting = [deque() for _ in range(26)]
count = 0
for i in range(n):
for c_idx in range(26):
if len(active[c_idx]) == 0:
continue
if active[c_idx][0] < i - r:
active[c_idx].popleft()
for c_idx in range(26):
if len(waiting[c_idx]) == 0:
continue
if waiting[c_idx][0] <= i - l:
active[c_idx].append(waiting[c_idx].popleft())
current_idx = ord(s[i]) - ord("a")
count += len(active[current_idx])
waiting[current_idx].append(i)
print(count)
さらに、deque管理より単純な「有効区間内の文字数カウント」に置き換えられます。
入力文字列sのi番目に対して、次を管理していきます。
-
active_count[c]:現在のiに対して、$L \leq i - j \leq R$を満たす、文字cの過去インデックスjの個数
以下を繰り返すことで求められます。
-
j = i - Lをactive_countに加える。 -
j = i - R - 1を active_count から引く。 -
active_count[s[i]]を答えに加える。
main.py (C - Comfortable Distance)
n, l, r = map(int, input().split())
s = input()
active_count = [0 for _ in range(26)]
count = 0
for i in range(n):
add_idx = i - l
if add_idx >= 0:
active_count[ord(s[add_idx]) - ord("a")] += 1
remove_idx = i - r - 1
if remove_idx >= 0:
active_count[ord(s[remove_idx]) - ord("a")] -= 1
count += active_count[ord(s[i]) - ord("a")]
print(count)
D - Make Target 2
$L \leq x \leq R$に対して、次の3つの個数を合計すればよいです。
- $D \leq y \leq |x| + 1$を満たす$y$のうち、偶数の個数
- $\max(-|x|, D) \leq y \leq \min(|x|, U)$を満たす$y$の個数 ($x$が偶数の場合のみ)
- $|x| + 1 \leq y \leq U$を満たす$y$のうち、偶数の個数
main.py (D - Make Target 2)
# iからjまでの個数を数える関数
def count_between(i, j):
if i > j:
return 0
return j - i + 1
# iからjまでの偶数の個数を数える関数
def even_count_between(i, j):
if i > j:
return 0
if i % 2:
return (j - i + 1) // 2
return (j - i) // 2 + 1
l, r, d, u = map(int, input().split())
count = 0
for x in range(l, r + 1):
count += even_count_between(d, min(-abs(x) - 1, u))
if x % 2 == 0:
count += count_between(max(-abs(x), d), min(abs(x), u))
count += even_count_between(max(abs(x) + 1, d), u)
print(count)
参考にしたサイト等
-
リストの
ord(c)-97番目に情報を格納しています。ord('a') == 97です。 ↩