AtCoder Beginner Contest 451の解答等の速報的まとめ
A問題
問題文のまま
A
print("No" if len(input()) % 5 else "Yes")
B問題
集計して差を出力
B
n, m = map(int, input().split())
now = [0] * m
nxt = [0] * m
for _ in range(n):
a, b = map(lambda x:int(x) - 1, input().split())
now[a] += 1
nxt[b] += 1
for a_i, b_i in zip(now, nxt):
print(b_i - a_i)
C問題
SortedListにぶち込む
各要素は高々2回しか触らないので間に合う
C
from sortedcontainers import SortedList
s = SortedList([])
for _ in range(int(input())):
com, h = map(int, input().split())
if com == 1:
s.add(h)
else:
while s and s[0] <= h:
s.pop(0)
print(len(s))
D問題
長さを見つつDFSで9桁以下の数をすべて作成
D
lst = list()
keta = 0
x = 1
while x < 10 ** 9:
lst.append(str(x))
x *= 2
s = set()
def dfs(now):
global s
for l_i in lst:
nxt = now + l_i
if len(nxt) <= 9:
s.add(int(nxt))
if len(nxt) <= 8:
dfs(nxt)
dfs("")
ans = sorted(s)
print(ans[int(input()) - 1])
E問題
選ぶ辺は距離が短いほうからループにならない$N-1$本の辺
各頂点からDFSで条件を満たすか判定
E
from collections import deque
class UnionFind:
"""
URL : https://note.nkmk.me/python-union-find/
"""
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
n = int(input())
data = list()
for i in range(n - 1):
a = list(map(int, input().split()))
for j, a_i in enumerate(a, i + 1):
data.append((a_i, i, j))
data.sort()
UF = UnionFind(n)
edge = [list() for _ in range(n)]
cnt = 0
for w_i, i, j in data:
if not UF.same(i, j):
UF.union(i, j)
edge[i].append((j, w_i))
edge[j].append((i, w_i))
cnt += 1
if cnt >= n - 1:
break
dist = list()
for start in range(n):
check = [False] * n
dist_i = [-1] * n
q = deque()
q.append(start)
check[start] = True
dist_i[start] = 0
while q:
now = q.popleft()
for to, w_to in edge[now]:
if check[to]:
continue
dist_i[to] = dist_i[now] + w_to
check[to] = True
q.append(to)
dist.append(dist_i)
ans = "Yes"
for w_i, i, j in data:
if dist[i][j] != w_i:
ans = "No"
print(ans)