0
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?

AtCoder Beginner Contest 177をPythonで解く

0
Posted at

AtCoder Beginner Contest 177の問題をPythonで解いてみました。

A - Don't be late

たどり着けるかどうかを計算します。
計算が整数の範囲でやれるように $D \leq T \times S$ という条件式を使用しています。

main.py (A - Takoyaki)
d, t, s = map(int, input().split())

if d <= t * s :
  print("Yes")
else:
  print("No")

B - Substring

$S$の可能な位置に$T$を重ねて、文字が異なる箇所の個数を数えます。
可能な位置の全通りを確認して、文字が異なる箇所の最小値が答えです。

main.py (B - Substring)
s = input()
t = input()

# ans を len(t) で初期化
# 最悪ケースでは t の全文字を置換する必要があるため
ans = len(t)

# s の各位置に t を重ねて、文字が異なる箇所の個数を数える
for i in range(len(s) - len(t) + 1):
    diff = 0
    # t の各文字 j を比較し、s[i+j] と t[j] が異なれば差分をカウント
    for j in range(len(t)):
        if s[i + j] != t[j]:
            diff += 1
    # 現在の最小値と比較して更新
    ans = min(ans, diff)

print(ans)

C - Sum of product of pairs

愚直に計算すると$O(N^2)$となってしまいます。

そこで、$i = 1, \ldots N - 1$に対して、$A_i$と$A_{i + 1} + \cdots + A_N$を掛け合わせた総和を求めることを考えます。
次のような手順で処理すると、区間和$A_{i + 1} + \cdots + A_N$を効率よく求められます。

  1. 最初に、$A_1 + \cdots + A_N$ を計算する。
  2. 1.で計算した値を利用して、$i = 0$に対する計算を行う。
  3. 1.で計算した値から$A_1$を引いた値を利用して、$i = 1$に対する計算を行う。
  4. 3.で計算した値から$A_2$を引いた値を利用して、$i = 2$に対する計算を行う。
main.py (C - Sum of product of pairs)
# 入力
n = int(input())
a = list(map(int, input().split()))
MOD = 10**9 + 7

# a[1] + a[2] + ... + a[n-1] を初期的に計算
suffix_sum = sum(a[1:]) if n >= 2 else 0

# 結果を保持する変数
result = 0

# 0 .. n-2 に対して、a[i] * (a[i+1] + ... + a[n-1]) を加算していく
for i in range(n - 1):
    result = (result + a[i] * suffix_sum) % MOD

    # 次の i では a[i+1] を除いた和を使う
    suffix_sum -= a[i + 1]

# 結果を出力
print(result)

あるいは、和の二乗の展開を利用すると、次のように書けます。

\sum_{i < j} A_i A_j = \frac{\left( \sum_i A_i \right)^2 - \sum_i A_i^2}{2}
main.py (C - Sum of product of pairs)
n = int(input())
a = list(map(int, input().split()))

print(((sum(a)**2 - sum([x**2 for x in a]))//2) % (10**9 + 7))

D - Friends

友達関係を辿って辿り着ける人は友達であるということから、$N$人の人は最終的には友達同士で結成された いくつかの「友達集合」 に分けられます。

ここで、もし同じ「友達集合」に所属する人同士を同じグループに配置してしまうと、その人達は友達同士になってしまうため、条件を満たすことが出来ません。
よって、最も人数の多い「友達集合」の人数を$K$とすると、必要なグループ数は最低でも$K$です。
他の各「友達集合」についても、$1$人ずつ順番にグループを割り振っていけばよいので、求める数は$K$です。

$K$を求める方法として、ここでは幅優先探索(breadth first search; BFS)と呼ばれる方法を用います。

main.py (D - Friends)
from collections import deque

# 入力
# n, m は入力変数のためそのまま使用する(ルール指定)
n, m = map(int, input().split())

# 隣接リスト(1-indexed)
adj = [[] for _ in range(n + 1)]
for _ in range(m):
    a, b = map(int, input().split())
    adj[a].append(b)
    adj[b].append(a)

# 訪問済みフラグ
seen = [False] * (n + 1)

# 最大の友達グループサイズ(最低1)
max_group_size = 1

# 全頂点を起点にして各連結成分のサイズをBFSで求める
for i in range(1, n + 1):
    if seen[i]:
        continue

    # この頂点の連結成分を探索
    seen[i] = True
    dq = deque([i])
    group_size = 1

    while dq:
        node = dq.popleft()
        for nei in adj[node]:
            if seen[nei]:
                continue
            seen[nei] = True
            group_size += 1
            dq.append(nei)

    if group_size > max_group_size:
        max_group_size = group_size

print(max_group_size)

参考にしたサイト等

0
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
0
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?