💡

【ABC231】AtCoder Beginner Contest 231 A-D メモ【python】

2021/12/12に公開

https://atcoder.jp/contests/abc231

A - Water Pressure

0.01倍

a = int(input())
print(a / 100)

B - Election

リストに入れて出現回数をカウント。最大カウントの値を返す。

import collections

n = int(input())

n_list = []
for i in range(n):
    x = input()
    n_list.append(x)


c = collections.Counter(n_list)
a = c.most_common()[0]
print(a[0])

C - Counting 2

身長でソートしてから二部探索で対象の身長以上の境目を見つける。計算量はO(logN)。

import bisect

n, q = map(int, input().split())
a_list = list(map(int, input().split()))

q_list = []
for i in range(q):
    input_q = int(input())
    q_list.append(input_q)

a_sorted = sorted(a_list)

for value in q_list:
    ans = bisect.bisect_left(a_sorted, value)
    print(len(a_sorted) - ans)

公式解答の2つ目が賢すぎて嫉妬した。
https://atcoder.jp/contests/abc231/submissions/27805883

D - Neighbors

3回以上登場しない かつ 連結グラフにしたときに閉路を持たない(ループを持たない)条件を探す。閉路を求める場合はUnionFIndを使う。

from collections import defaultdict


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)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members

    def __str__(self):
        return "\n".join(f"{r}: {m}" for r, m in self.all_group_members().items())


n, m = map(int, input().split())

if m == 0:
    print("Yes")
    exit()

uf = UnionFind(n)
cnt = [0] * n

for i in range(m):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    if uf.same(u, v):
        print("No")
        exit()
    uf.union(u, v)
    cnt[u] += 1
    cnt[v] += 1
    if cnt[u] > 2 or cnt[v] > 2:
        print("No")
        exit()
print("Yes")

Discussion