3
2

More than 3 years have passed since last update.

atcoderで使えそうなpythonスニペット(随時追加していきます)

Last updated at Posted at 2019-11-17

atcoderで使えそうなpythonスニペット

こう言う細かいのも自分で書くのだるいな、と思ったので記事にまとめていきます。

入力各種。

import sys

def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

木の入力

n, q = LI()
G = [[] for _ in range(n)]
for a, b in LIR(n - 1):
    G[a - 1] += [b - 1]
    G[b - 1] += [a - 1]

一般のグラフの場合はLIR(n-1)の部分のn-1をmに変えます。

n = I()
G = []
for _ in range(n):
    G += [LI()]

隣接行列。こんぐらいその場でかけよとも思うが。

グラフ生成
どのようなグラフかをパッと把握するのに便利なライブラリ。

n = I()
G = nx.DiGraph() #無向グラフの時はnx.Graph()
for a, b in LIR(n - 1):
    G.add_edge(a-1, b-1)

nx.draw_networkx(G)
# 画像を保存する場合はplt.savefig('hoge.png')を追加
plt.show()

下の図のようになる。
graph.png

3
2
3

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
3
2