LoginSignup
3
3

AtCoder標準入力まとめ

Last updated at Posted at 2023-08-14

はじめに

AtCoderの標準入力セットは既にたくさんの方がまとめてくれていますが、int型とリスト内包表記を自分なりにわかりやすくまとめてみました。
作成途中なので随時更新していきます。

(1, N)行列データ(リスト内包表記なし)

入力

N
A1 A2 A3 … AN

入力例

3
2 3 5

コード例

sample.py
N = int(input())
A = list(map(int, input().split()))

#出力
print(A)
[2, 3, 5]

#unpackという手法を使うと以下のように出力されます
print(*A)
2 3 5

(N, 1)行列データ

入力

N M
A1
A2
A3

AN

入力例

3 3
2
3
5

コード例1(int型)

sample.py
N, M = map(int, input().split())
A = []
for _ in range(N):
    A.append(int(input()))

#出力
print(A)
[2, 3, 5]

コード例2(リスト内包表記)

sample.py
N, M = map(int, input().split())
A = [int(input()) for _ in range(N)]

#出力
print(A)
[2, 3, 5]

(N, M)行列データ

(N, M)行列データは行で格納する方法と列で格納する方法の2つがあります。
それぞれ、int型とリスト内包表記の2通りで格納することができます。

問題の入力部分(ABC315C)

Nカップのアイスクリームがあります、
iカップ目の味はFi、美味しさはSiです。

入力

N
F1 S1
F2 S2
︙ ︙
FN SN

入力例

4
1 4
2 10
2 8
3 6

コード例

[xi, yi]として格納(行で格納)

int型
1変数のとき

sample.py
N = int(input())
A = []
for _ in range(N):
    a = list(map(int, input().split()))
    A.append(a)

# 出力
print(A)  
[[1, 4], [2, 10], [2, 8], [3, 6]]

2変数の時

sample.py
N = int(input())
ice = []
for _ in range(N):
    F, S = map(int, input().split())
    ice.append((F, S))

# 出力
print(ice)  
[(1, 4), (2, 10), (2, 8), (3, 6)]

リスト内包表記

sample.py
N = int(input())
ice = [list(map(int, input().split())) for _ in range(N)]

# 出力
print(ice) 
[[1, 4], [2, 10], [2, 8], [3, 6]]

x,yを独立に格納(列で格納)

int型

sample.py
N = int(input())
F = []
S = []
for _ in range(N):
    f, s = map(int,input().split())
    F.append(f)
    S.append(s)

# 出力
print(F)  
[1, 2, 2, 3]
print(S)  
[4, 10, 8, 6]

リスト内包表記

sample.py
N = int(input())
ice = [map(int, input().split()) for _ in range(N)]
F, S = [list(i) for i in zip(*ice)]

# 出力
print(F)  
[1, 2, 2, 3]
print(S)  
[4, 10, 8, 6]

二次元配列として格納

二次元配列はグラフ問題や計算量を削減する際に使用されます。
今回の問題では味別にそれぞれ格納しています。

sample.py
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N):
    f, s = map(int, input().split())
    G[f - 1].append(s)

# 出力
print(G)  
[[4], [10, 8], [6], []]

味が1のものは4、味が2のものは10と8...という風に格納されています。

3
3
1

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
3