ABC177 - Atcoder/Python精進のための解説メモ
2022/12/27
ABC177 - A.Don't be late
AtCoder公式 | ABC177 - A.Don't be late解答
d, t, s = map(int, input().split())
print('Yes' if d / s <= t else 'No')
要点解説メモ
- =がどちらの判定になるかを常に意識して、条件分岐は書きたいね
ABC177 - B.Substring
AtCoder公式 | ABC177 - B.Substring解答
s = input()
t = input()
len_s = len(s)
len_t = len(t)
ans = len_t
for i in range(len_s - len_t + 1):
tmp = 0
for j in range(len_t):
if s[i + j] != t[j]:
tmp += 1
ans = min(ans, tmp)
print(ans)
要点解説メモ
- ansの初期値が想定される最大値としておく
- 文字数が少なく直感的に全探索でいけそうだが、計算量O(len(S)*len(T))で間に合うのをしっかり見極める
ABC177 - C.Sum of product of pairs
AtCoder公式 | ABC177 - C.Sum of product of pairs解答
n = int(input())
aaa = list(map(int, input().split()))
mod = 1000000007
acc = [0] * n
acc[n - 1] = aaa[n - 1]
ans = 0
for i in range(n - 2, 0, -1):
acc[i] = (acc[i + 1] + aaa[i]) % mod
for i in range(n - 1):
ans += aaa[i] * acc[i + 1] % mod
ans %= mod
print(ans)
別解
n = int(input())
aaa = list(map(int, input().split()))
mod = 1000000007
ans = 0
for a in aaa:
ans += a
ans %= mod
ans **= 2
ans %= mod
for a in aaa:
ans -= a ** 2 % mod
if ans < 0:
ans += mod
ans *= pow(2, -1, mod)
ans %= mod
print(int(ans))
要点解説メモ
- 前から累積和を使っても良いけど、後ろから累積しておいたほうが用途にはあってる
- a, b, cの3つで試すと、求める数はab+bc+caなので、(a+b+c)**2の変形でいける、別解に気づく
- 別解では割り算が出てくるので、modの逆元をとる必要がある
- Python3.8から、powで逆元が簡単に出せるようになったらしい、すごい
- 逆元を求める方法として、フェルマーの小定理とと拡張ユークリッドの互除法の2つを理解はしておく
ABC177 - D.Friends
AtCoder公式 | ABC177 - D.Friends解答
class UnionFind():
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)]
n, m = map(int, input().split())
u = UnionFind(n)
for _ in range(m):
a, b = map(int, input().split())
u.union(a - 1, b - 1)
print(max(u.size(i) for i in range(n)))
要点解説メモ
- UnionFindの典型問題
- さっとUnionFindが使えるように手元に用意しておくの大事
- 自分でも何回か書いて理解する