Edited at

AtCoderの問題を分類しました


はじめに

2019年1月から AtCoder を始めました。問題の復習と自分の技術力を分析するために、問題を解いて得られた知見をメモとして残しています。周りの方から「知見を共有して欲しい」「公開することでコードレビューされて、技術力がより高まるよ」などの意見を頂いたため、本記事を執筆する運びとなりました。


本記事について


記事の構成

本記事では分類観点を定義し、分類観点ごとに問題を分類しています。各分類観点では、サンプルコード(入力/実行結果)と解答例を記載しています。サンプルコード(入力/実行結果)と解答例の定義は下記の通りです。


  • サンプルコード:問題から得られた知見と検証によって得られた知見を整理したコード

  • 入力:サンプルコードの入力例

  • 実行結果:サンプルコードの実行結果

  • 解答例:AtCoderに提出したACのコード(一部、TLEのコードがあります。その場合は、「解答例(TLE)」と記載しています。)


実行環境

サンプルコードは下記環境で動作することを確認しています。

$ python --version

Python 3.6.4

解答例はAtCoderの下記言語でACになることを確認しています。

Python3 (3.4.3)


分類観点の定義

分類観点の定義は下記の通りです。1つの問題から複数の観点で分類できる問題は、複数の観点に分類します。


観点
観点内容

第1章
文法観点
文法を知っていれば解ける問題

第2章
データ型観点
データ型を知っていれば解ける問題

第3章
データ構造観点
データ構造を知っていれば解ける問題

第4章
基本処理観点
基本処理(よく使われる関数とメソッド)を知っていれば解ける問題

第5章
応用処理観点
応用処理(よく使われる処理方法)を知っていれば解ける問題

第6章
アルゴリズム観点
アルゴリズムを知っていれば解ける問題

第7章
計算量観点
計算量を工夫すれば解ける問題

第8章
数学観点
数学的知見を知っていれば解ける問題

第9章
カテゴリ観点
カテゴリ特有の解き方を知っていれば解ける問題

第10章
実装観点
実装方式を知っていれば解ける問題


分類する問題の範囲

分類する問題の範囲は下記の通りです。ABC-C問題とARC-A問題は一部問題が同じです。同じ問題の場合、ABC-C問題として扱います。


  • ABC-A問題(ABC001 - ABC122)

  • ABC-B問題(ABC001 - ABC122)

  • ABC-C問題(ABC001 - ABC122)

  • ARC-A問題(ARC001 - ARC103)


分類する対象の問題

本記事では、上記分類範囲で示したすべての問題が記載されているわけではありません。私が上記分類観点で知見が得られた問題のみを記載しています。


本記事の対象者

本記事では下記のような方を読者として想定しています。


  • AtCoderを始めようとしている方(使用言語の候補としてPython3がある方)

  • AtCoderをPython3以外でやっている方(使用言語をPython3にしたい方)

  • Python3のコードバリデーションを参考にしたい方

  • Python3の仕様に依らない問題分類を参考にしたい方

  • 本記事の内容 / コードをレビューして頂ける方


コーディング規約

利用しているコーディング規約はありません。しかし、下記の方針でコーディングを行っています。※厳密に下記コーディング方針でコーディングしている訳ではありません。


  • インデントは4とする

  • 1行の長さは定義しない

  • 空行はしない(可読性のために一部入れることもある)

  • importは行を分けて定義する

  • クオーテーションはダブルクオテーションで統一する

  • 不要な半角スペースは入れない(可読性のために一部入れることもある)

  • 1処理は1行で記載する

  • 変数 / 型を1行で定義できる場合、1行で定義する

  • if文 / for文 / while文の処理行数が1行の場合、文と処理を1行でコーディングする

  • 命名規則はない

  • 自分の直感に合うコーディングをする


記事の更新方針

分類範囲の問題で未分類 / 未解答の問題があります。また、今後はABC-D問題 / AGC-A問題を解く予定です。そのため、本記事は今後、下記の更新する予定です。更新情報は編集履歴より確認をお願い致します。


  • 未分類問題の追加

  • 未解答問題の追加

  • ABC-D問題の追加

  • AGC-A問題の追加


知的財産権

本記事に記載しているコードはすべて私が作成したコードです。また、AtCoderにおける知的財産権は下記の通りです。


知的財産権

1.本サービスに対して投稿されたプログラムの所有権と著作権は、そのプログラムを作成したユーザに帰属します

2.本サービスを構成する文章、画像、プログラムその他のデータ等についての一切の権利(所有権、知的財産権、肖像権、パブリシティー権等)は、ユーザ自身が作成したものを除き、弊社又は当該権利を有する第三者に帰属しています

3.ユーザ自身が作成した著作物を本サービスを通じて掲載した場合、弊社が宣伝告知等に利用することを許諾するものとします。また、かかる使用に際して、当該ユーザは著作者人格権を行使しないものとします


本記事に記載しているコードを私的利用する場合、自由に活用して頂いて構いません。また、作成したコードは Github で公開しています。コードを転用する / 商業利用する場合は、本記事のコメント欄 / メール / Twitter で事前にご相談をお願い致します。

学習方法の特性上「他人のコードに酷似している」ことがあります。気分を害される方がいましたら、相談の上で引用元の記載 / 記事の更新 / 文章の削除等に対応しますので、ご連絡をお願い致します。※学習方法は ブログ に記載しています。


最後に

最後となりましたが、読者の方におかれましては初心者競プロerの成長過程と思い、温かく見守って頂けると幸いです。また、このような学習環境を提供して頂いている AtCoder社、SNS等で関わって頂いている競プロerの方に感謝を申し上げます。


編集履歴


1.0版:2019年02月26日(火)


  • 初版公開


1.1版:2019年03月03日(日)

1.1版内容(クリックして表示)


  • 本記事に「変更管理」項目(本項目)を追加(変更管理をするため)

  • divmod追加(平方根の整数部と小数部の算出、組み込み関数)

  • string.ascii_lowercase追加(文字の集合)

  • 問題追加(ABC-D問題114, 115, 118, 119)

  • 記載修正(ABC063 B - Varied⇒ABC063 A - Restricted)

  • スペル修正(入力処理、Raw⇒Row)

  • スペル修正(利用規約、AtCode⇒AtCoder)

  • スペル修正(約数、Prime⇒Divisor)

  • 「記事の更新方針」項目に「AGC-A問題の追加」を追加(AGCコンテスト対策として)



1.2版:2019年03月10日(日)

1.2版内容(クリックして表示)


  • 本章を「変更管理」から「編集履歴」に変更

  • 「実装観点」を「文法観点」「データ型観点」「データ構造観点」に再編し、分類

  • 「入力処理」の入力部分を「入力例」として外出し

  • 「カテゴリ観点」を新規作成

  • 「処理観点」の一部項目を「カテゴリ観点」に移動

  • 正規表現を処理観点に移動

  • サンプルコードの不要な空行を削除

  • 一部の参考サイトを削除(参考にしていないため)

  • レート情報を削除(参考にしていないため)

  • 「複素数」の項目を削除(利用していないため)

  • 記載修正(divmod、enumerate⇒divmod)



1.3版:2019年03月17日(日)

1.3版内容(クリックして表示)


  • 章と節に番号を振り分け

  • 「はじめに」と「分類する対象の問題」を修正

  • ABC-A問題を再振り分け



1.4版:2019年03月24日(日)

1.4版内容(クリックして表示)


  • ABC-A問題を再振り分け

  • ABC-B問題を再振り分け



1.5版:2019年03月31日(日)

1.5版内容(クリックして表示)


  • ABC-B問題を再振り分け

  • 細かい文章の修正



第1章 文法観点


1.1 出力処理


int型


  • 整数を出力する


サンプルコード

print(10)



実行結果

10



  • 整数を変数に格納して出力する


サンプルコード

x=20

print(x)


実行結果

20



float型


  • 浮動小数点型を出力する


サンプルコード

print(2.9)



実行結果

2.9



  • 浮動小数を変数に格納して出力する


サンプルコード

x=3.5

print(x)


実行結果

3.5



str型


  • 文字列を出力する


サンプルコード

print("Hello World!")



実行結果

Hello World!



  • 文字列を変数に格納して出力する


サンプルコード

s="Hello World!"

print(s)


実行結果

Hello World!



  • 文字列の変数のインデックスを指定して文字を出力する


サンプルコード

s="Hello World!"

print(s[0])


実行結果

H



サンプルコード

s="Hello World!"

print(s[11])


実行結果

!


ABC041 A - 添字


解答例

print(input()[int(input())-1])



解答例

s=input()

i=int(input())
print(s[i-1])

ABC048 A - AtCoder *** Contest


解答例

print("A%sC"%input()[8])



解答例

print("A"+input()[8]+"C")



list型


  • 1次元リストを出力する


サンプルコード

Lists=[1,2,3,4,5]

print(List)


実行結果

[1, 2, 3, 4, 5]



  • 1次元リストの各要素を出力する


サンプルコード

Lists=[1,2,3,4,5]

for List in Lists:
print(List)


実行結果

1

2
3
4
5


サンプルコード

Lists=[1,2,3,4,5]

print(*List)


実行結果

1 2 3 4 5



  • 1次元リストのインデックス指定して各要素を出力する


サンプルコード

List=[1,2,3,4,5]

for i in range(len(List)):
print(List[i])


実行結果

1

2
3
4
5


  • 2次元リストを出力する


サンプルコード

List=[[1,2,3],[4,5,6]]

print(List)


実行結果

[[1, 2, 3], [4, 5, 6]]



  • 2次元リストの各行を出力する


サンプルコード

Lists=[[1,2,3],[4,5,6]]

for List in Lists:
print(List)


実行結果

[1, 2, 3]

[4, 5, 6]


  • 2次元リストの各要素を出力する


サンプルコード

List=[[1,2,3],[4,5,6]]

for Row in List:
for Col in Row:
print(Col)


実行結果

1

2
3
4
5
6


  • 2次元リストの各要素をインデックス指定して出力する


サンプルコード

List=[[1,2,3],[4,5,6]]

for i in range(len(List)):
for j in range(len(List[i])):
print(List[i][j])


実行結果

1

2
3
4
5
6

ABC046 B - 文字列大好きいろはちゃんイージー / Iroha Loves Strings (ABC Edition)


解答例

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

s=sorted([input() for i in range(n)])
print(*s,sep="")


解答例

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

s=sorted([input() for i in range(n)])
print("".join(s))


区切り文字の指定


  • 半角スペース(デフォルト)


サンプルコード

a=1

b=2
c=3
print(a,b,c)


実行結果

1 2 3



  • 改行を指定する


サンプルコード

a=1

b=2
c=3
print(a,b,c,sep='\n')


実行結果

1

2
3


  • カンマを指定する


サンプルコード

a=1

b=2
c=3
print(a,b,c,sep=',')


実行結果

1,2,3



  • 区切り文字なしを指定する


サンプルコード

a=1

b=2
c=3
print(a,b,c,sep='')


実行結果

123


ABC046 B - 文字列大好きいろはちゃんイージー / Iroha Loves Strings (ABC Edition)


解答例

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

s=sorted([input() for i in range(n)])
print(*s,sep="")


末尾文字の指定


  • 改行(デフォルト)


サンプルコード

print("a")

print("b")


実行結果

a

b


  • 末尾文字なしを指定する


サンプルコード

print("a",end="")

print("b")


実行結果

ab


ABC058 B - ∵∴∵


解答例

o=list(input())

e=list(input())+[""]
for x,y in zip(o,e):print(x+y,end="")


1.2 入力処理


1行 / 1列


  • 整数を変数に格納する


入力

2



サンプルコード

N=int(input())

print(N)


実行結果

2


ABC007 A - 植木算


解答例

print(int(input())-1)



  • 文字列を1つの変数に格納する


入力

Hello world!



サンプルコード

s=input()

print(s)


実行結果

Hello world!



  • 文字列を複数の変数に格納する


入力

1234



サンプルコード

a,b,c,d=input() # 1234を整数(int)型ではなく、文字列(str)型で変数に格納する

print(a,b,c,d)


実行結果

1 2 3 4



入力

abcd



サンプルコード

a,b,c,d=input()

print(a,b,c,d)


実行結果

a b c d


ABC020 A - クイズ


解答例

print("ABC" if input()=="1" else "chokudai")


ABC070 A - Palindromic Number


解答例

a,b,c=input()

print("Yes" if a==c else "No")


解答例

n=input()

print("Yes" if n[0]==n[2] else "No")

ABC079 A - Good Integer


解答例

a,b,c,d=input()

print("Yes" if a==b==c or b==c==d else "No")


解答例

n=input()

print("Yes" if n[0]==n[1]==n[2] or n[1]==n[2]==n[3] else "No")


1行 / C列


  • 整数を複数の変数に格納する


入力

1 2



サンプルコード

a,b=map(int,input().split())

print(a)
print(b)


実行結果

1

2

ABC012 A - スワップ


解答例

a,b=map(int,input().split())

print(b,a)


  • 文字列を複数の変数に格納する


入力

Hello world!



サンプルコード

a,b=input().split()

print(a)
print(b)


実行結果

Hello

world!

ABC012 A - スワップ


解答例

a,b=input().split()

print(b,a)

ABC051 A - Haiku

a,b,c=input().split(",")

print(a,b,c)

ABC056 A - HonestOrDishonest


解答例

a,_,b=input()

print("DH"[a==b])

ABC079 A - Good Integer


解答例

a,b,c,d=input()

print("Yes" if a==b==c or b==c==d else "No")

ABC110 A - Maximize the Formula


解答例

A,B,C=sorted(map(int,input().split()))

print(10*C+B+A)

ABC116 A - Right Triangle


解答例

a,b,c=map(int,input().split())

print(a*b//2)


  • リストに整数を格納する


入力

1 2 3 4 5



サンプルコード

List=list(map(int,input().split()))

print(List)


実行結果

[1, 2, 3, 4, 5]



入力

1 2 3 4 5



サンプルコード

List=[int(i) for i in input().split()]

print(List)


実行結果

[1, 2, 3, 4, 5]



  • リストに文字列を格納する


入力

Hello world !



サンプルコード

List=list(input().split())

print(List)


実行結果

['Hello', 'world', '!']



入力

Hello world !



サンプルコード

List=[i for i in input().split()]

print(List)


実行結果

['Hello', 'world', '!']



  • アンパックを使ってリストに格納する

ABC069 B - i18n


解答例

a,*b,c=input()

print(a+str(len(b))+c)

ABC051 A - Haiku


解答例

print(*input().split(','))


ABC103 A - Task Scheduling Problem


解答例

*a,=map(int,input().split())

print(max(a)-min(a))


R行 / 1列


  • 整数を複数の変数に格納する


入力

1

2


サンプルコード

a=int(input())

b=int(input())
print(a,b)


実行結果

1 2



入力

1

2


サンプルコード

a,b=[int(input()) for i in range(2)]

print(a,b)


実行結果

1 2


ABC044 A - 高橋君とホテルイージー / Tak and Hotels (ABC Edit)


解答例

n,k,x,y=(int(input()) for i in [0]*4)

print(n*x-(x-y)*max(n-k,0))

ABC087 A - Buying Sweets


解答例

x,a,b=[int(input()) for _ in range(3)]

print((x-a)%b)

ABC092 A - Traveling Budget


解答例

a,b,c,d=[int(input()) for _ in range(4)]

print(min(a,b)+min(c,d))


  • リストに格納する


入力

1

2
3
4
5


サンプルコード

List=[int(input()) for i in range(5)]

print(List)


実行結果

[1, 2, 3, 4, 5]


ABC085 B - Kagami Mochi


解答例

print(len(set([int(input()) for _ in range(int(input()))])))


ABC091 B - Two Colors Card Game


解答例

n=[input() for _ in range(int(input()))]

m=[input() for _ in range(int(input()))]
l=list(set(n))
print(max(0,max(n.count(l[i])-m.count(l[i]) for i in range(len(l)))))

ABC115 B - Christmas Eve Eve


解答例

l=[int(input()) for _ in range(int(input()))]

print(sum(l)-int(max(l)/2))


  • 入力行数(Row=5)が指定され、リストに整数を格納する


入力

5

0
1
2
3
4


サンプルコード

Row=int(input()) 

List=[int(input()) for i in range(Row)]
print(List)


実行結果

[0, 1, 2, 3, 4]


ABC031 B - 運動管理


解答例

l,w=map(int,input().split())

n=int(input())
for i in range(n):
a=int(input())
print(l-a if l>a else "0" if w>=a else "-1")

ABC112 B - Time Limit Exceeded


解答例

N,T=map(int,input().split())

m=1001
for i in range(N):
c,t=map(int,input().split())
if t<=T:m=min(m,c)
print("TLE" if m==1001 else m)


  • 入力行数(Row=5)が指定され、リストに文字列を格納する


入力

5

a
b
c
d
e


サンプルコード

Row=int(input()) 

List=[input() for i in range(Row)]
print(List)


実行結果

['a', 'b', 'c', 'd', 'e']



R行 / C列


  • 複数のリストに格納する(入力時に行数(Row)を指定する)


入力

3

0 a
1 b
2 c


サンプルコード

Row=int(input())

Number=[]
Alphabet=[]
for i in range(Row):
n,a=input().split()
Number.append(int(n))
Alphabet.append(a)
print(Number)
print(Alphabet)


実行結果

[0, 1, 2]

['a', 'b', 'c']

ABC033 B - 町の合併


解答例

n=int(input())

S=[]
P=[]
for i in range(n):
s,p=input().split()
S.append(s)
P.append(int(p))
if max(P)>sum(P)/2:print(S[P.index(max(P))])
else:print("atcoder")


  • 2次元リストに格納する(入力時に行数(Row)を指定する)


入力

3

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15


サンプルコード

Row=int(input())

List=[list(map(int,input().split())) for i in range(Row)]
print(List)


実行結果

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]



入力

3

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15


サンプルコード

Row=int(input())

List=[[int(j) for j in input().split()] for i in range(Row)]
print(List)


実行結果

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]



入力

3

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15


サンプルコード

Row=int(input())

List=[]
for i in range(Row):
List.append(list(map(int,input().split())))
print(List)


実行結果

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]



  • 2次元リストに格納する(入力時に行数が指定されない)


入力

1 2 3 4 5

6 7 8 9 10
11 12 13 14 15


サンプルコード

List=[list(map(int,input().split())) for i in range(3)]

print(List)


実行結果

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]



  • 1次元リストに格納する


入力

1 2 3 4 5

6 7 8 9 10
11 12 13 14 15


サンプルコード

List=[]

for i in range(3):
List+=list(map(int,input().split()))
print(List)


実行結果

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]



  • 変数に格納する


入力

1 2 3 4 5

6 7 8 9 10
11 12 13 14 15


サンプルコード

a=" ".join([input() for i in [0]*3])

print(a)


実行結果

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15


ABC037 B - 編集


解答例

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

a=[0]*n
for i in range(q):
l,r,t=map(int,input().split())
for i in range(l,r+1):a[i-1]=t
print(*a,sep="\n")

ABC094 B - Toll Gates


解答例

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

s=sum(int(i)<x for i in input().split())
print(min(s,m-s))

ABC118 B - Foods Loved by Everyone


解答例

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

S=set(range(1,m+1))
for i in range(n):
K,*A=map(int,input().split())
S&=set(A)
print(len(S))

ABC121 B - Can you solve this?


解答例

N,M,C=map(int,input().split())

B=list(map(int,input().split()))
count=0
for i in range(N):
A=list(map(int,input().split()))
p=C
for j in range(M):p+=A[j]*B[j]
if p>0:count+=1
print(count)


1.3 四則演算


加法


  • 加法:addition


サンプルコード

print(1+2)



実行結果

3


ABC063 A - Restricted


解答例

a,b=map(int,input().split())

print(a+b if a+b<10 else "error")

ABC110 A - Maximize the Formula


解答例

A,B,C=sorted(map(int,input().split()))

print(10*C+B+A)


解答例

l=list(map(int,input().split()))

print(sum(l)+max(l)*9)


減法


  • 減法:subtraction


サンプルコード

print(2-1)



実行結果

1


ABC013 B - 錠


解答例

x=abs(int(input())-int(input()))

print(min(x,10-x))

ABC073 B - Theater


解答例

print(sum(1-eval(input().replace(" ","-")) for _ in range(int(input()))))


ABC001 A - 積雪深差


解答例

print(int(input())-int(input()))


ABC007 A - 植木算


解答例

print(int(input())-1)


ABC008 A - アルバム


解答例

s,t=map(int,input().split())

print(t-s+1)

ABC058 A - ι⊥l


解答例

a,b,c=map(int,input().split())

print("YES" if b-a==c-b else "NO")

ABC072 A - Sandglass2


解答例

x,t=map(int,input().split())

print("0" if x-t<0 else x-t)

ABC074 A - Bichrome Cells


解答例

print(int(input())**2-int(input()))


ABC076 A - Rating Goal


解答例

print(-int(input())+2*int(input()))


ABC084 A - New Year


解答例

print(48-int(input()))


ABC103 A - Task Scheduling Problem


解答例

A=list(map(int,input().split()))

print(max(A)-min(A))


解答例

a,b,c=sorted(map(int,input().split()))

print(c-a)

ABC106 A - Garden


解答例

a,b=map(int,input().split())

print(a*b-(a+b-1))

ABC107 A - Train


解答例

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

print(n-i+1)


乗法


  • 乗算:multiplication


サンプルコード

print(3*2)



実行結果

6


ABC004 A - 流行


解答例

print(int(input())*2)


ABC017 A - プロコン


解答例

s1,e1=map(int,input().split())

s2,e2=map(int,input().split())
s3,e3=map(int,input().split())
print((s1*e1+s2*e2+s3*e3)//10)

ABC028 A - テスト評価


解答例

print((["Bad"]*6+["Good"]*3+["Great"]+["Perfect"])[int(input())//10])


ABC031 A - ゲーム


解答例

a,d=map(int,input().split())

print(a*d+max(a,d))


解答例

a,d=map(int,input().split())

print(max(a,d)*(min(a,d)+1))

ABC052 A - Two Rectangles


解答例

a,b,c,d=map(int,input().split())

print(max(a*b,c*d))

ABC069 A - K-City


解答例

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

print((n-1)*(m-1))

ABC076 A - Rating Goal


解答例

print(-int(input())+2*int(input()))


ABC106 A - Garden


解答例

a,b=map(int,input().split())

print(a*b-(a+b-1))

ABC115 A - Christmas Eve Eve Eve


解答例

print("Christmas"+" Eve"*(25-int(input())))


ABC121 A - White Cells


サンプルコード

H,W=map(int,input().split())

h,w=map(int,input().split())
print((H-h)*(W-w))


べき乗 / 指数


  • べき乗:power


サンプルコード

print(2**3)



実行結果

8



サンプルコード

print(10**9+7)



実行結果

1000000007


ABC068 B - Break Number


解答例

print(2**(len(bin(int(input())))-3))



解答例

n=int(input())

ans=1
for i in range(7):
if 2**i<=n:ans=2**i
print(ans)

ARC036 A - 数え上げ


解答例

print(10**int(input())+7)


ABC097 B - Exponential


解答例

x=int(input())

c=1
for b in range(1,x):
for p in range(2,x):
if b**p<=x:c=max(c,b**p)
else:break
print(c)

ABC074 A - Bichrome Cells


解答例

print(int(input())**2-int(input()))



平方根 / べき根


  • 平方根:square root


サンプルコード

print(4**.5)



実行結果

2.0



サンプルコード

print(4**(1/2))



実行結果

2.0


ABC039 B - エージェント高橋君


解答例

print(int(int(input())**.25))


ABC077 B - Around Square


解答例

print(int(int(input())**.5)**2)


ABC086 B - 1 21


解答例

print("No" if int(input().replace(" ",""))**.5%1 else "Yes")



解答例

c=int(input().replace(" ",""))

print("Yes" if c==int(c**.5)**2 else "No")


階乗


  • 階乗:factorial


サンプルコード

import math

print(math.factorial(5))


実行結果

120


ABC055 B - Training Camp


解答例

import math

print(math.factorial(int(input()))%(10**9+7))


解答例

ans=1

n=int(input())
for i in range(1,n+1):
ans*=i
ans=ans%(10**9+7)
print(ans)


除法


  • 除法:division


サンプルコード

print(6/3)



実行結果

2.0



小数点切り捨て


  • 床関数(切り捨て):floor


サンプルコード

print(5//3)



実行結果

1



サンプルコード

import math

print(math.floor(5/3))


実行結果

1



サンプルコード

print(6//3)



実行結果

2


ABC078 B - ISU


解答例

x,y,z=map(int,input().split())

print((x-z)//(y+z))

ABC095 B - Bitter Alchemy


解答例

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

l=[int(input()) for _ in range(n)]
print(n+((x-sum(l))//min(l)))

ABC111 B - AtCoder Beginner Contest 111


解答例

N=int(input())

print((((N-1)//111)+1)*111)

ABC005 A - おいしいたこ焼きの作り方


解答例

x,y=map(int,input().split())

print(y//x)

ABC030 A - 勝率計算


解答例

a,b,c,d=map(int,input().split())

T,A=b/a,d/c
print("TAKAHASHI" if T>A else "AOKI" if T<A else "DRAW")

ABC055 A - Restaurant


解答例

n=int(input())

print(n*800-n//15*200)

ABC089 A - Grouping 2


解答例

print(int(input())//3)


ABC108 A - Pair


解答例

print(int(input())**2//4)



解答例

k=int(input())

print((k//2)*((k+1)//2))

ABC113 A - Discount Fare


解答例

x,y=map(int,input().split())

print(x+y//2)

ABC116 A - Right Triangle


解答例

a,b,c=map(int,input().split())

print(a*b//2)

ABC117 A - Entrance Examination


解答例

print(eval(input().replace(" ","/")))



小数点切り上げ


  • 天井関数(切り上げ):ceil


サンプルコード

print(-(-5//3))



実行結果

2



サンプルコード

import math

print(math.ceil(5/3))


実行結果

2



サンプルコード

print(-~(4+5)//2)



実行結果

5



サンプルコード

print(-~(5+5)//2)



実行結果

5


ABC015 B - 高橋くんの集計


解答例

n=int(input())

a=list(map(int,input().split()))
print(-(-sum(a)//(n-a.count(0))))

ABC111 B - AtCoder Beginner Contest 111


解答例

print(-int(input())//111*-111)


ABC009 A - 引越し作業


解答例

print(-(-int(input())//2))



解答例

print((int(input())+1)//2)


ABC024 A - 動物園


解答例

print(5//3+(5%3>0))


ABC036 A - お茶


解答例

a,b=map(int,input().split())

print(-(-b//a))

ABC082 A - Round Up the Mean


解答例

print(-~sum(map(int,input().split()))//2)



解答例

a,b=map(int,input().split())

print(-~(a+b)//2)

ABC120 A - Favorite Sound


解答例

a,b,c=map(int,input().split())

print(min(c,b//a))


四捨五入


  • 四捨五入:rounding


サンプルコード

print(round(5/3))



実行結果

2



剰余


  • 剰余:modulo


サンプルコード

print(7%3)



実行結果

1


ABC099 C - Strange Bank


解答例

N=int(input())

ans=N
for i in range(N+1):
cnt=0
while i>0:
cnt+=i%6
i//=6
j=N-i
while j>0:
cnt+=j%9
j//=9
ans=min(ans,cnt)
print(ans)

ABC034 B - ペア


解答例

n=int(input())

print(n+1 if n%2 else n-1)

ABC041 B - 直方体


解答例

print(eval(input().replace(" ","*"))%(10**9+7))


ABC060 B - Choose Integers


解答例

a,b,c=map(int,input().split())

print("YES" if any((a*i)%b==c for i in range(1,b+1)) else "NO")

ABC008 A - たこ焼き買えるかな?


解答例

N=int(input())

print(N//10*100+min(100,N%10*15)

ABC009 A - 引越し作業


解答例

n=int(input())

print(n//2+n%2)

ABC011 A - 来月は何月?


解答例

print(int(input())%12+1)


ABC014 A - けんしょう先生のお菓子配り


解答例

print(-int(input())%int(input()))



解答例

a=int(input())

b=int(input())
print((((a//b)+1)*b-a) if a%b!=0 else "0")

ARC016 A - 12月6日


解答例

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

print("NO" if m%d else "YES")

ARC035 A - テレビ


解答例

w,h=map(int,input().split())

print("16:9" if w*h%144==0 else "4:3")

ABC054 A - One Card Poker


解答例

a,b=map(int,input().split())

print("Draw" if a==b else "Bob" if (a+13)%15<(b+13)%15 else "Alice")

ABC057 A - Remaining Time


解答例

print(sum(map(int,input().split()))%24)


ABC064 A - RGB Cards


解答例

print("NO" if int(input()[::2])%4 else "YES")


ABC067 A - Sharing Cookies


解答例

a,b=map(int,input().split())

print("Impossible" if a*b*(a+b)%3 else "Possible")

ABC081 A - Placing Marbles


解答例

print(int(input())%9)


ABC086 A - Product


解答例

a,b=map(int,input().split())

print("Odd" if a*b%2 else "Even")

ABC087 A - Buying Sweets


解答例

x,a,b=[int(input()) for _ in range(3)]

print((x-a)%b)

ABC088 A - Infinite Coins


解答例

N=int(input())

A=int(input())
print("Yes" if N%500<=A else "No")

ABC102 A - Multiple of 2 and N


解答例

n=int(input())

print(n+n%2*n)


解答例

N=int(input())

print(N if N%2==0 else N*2)

ABC105 A - AtCoder Crackers


解答例

print((eval(input().replace(" ","%"))>0)+0)



解答例

N,K=map(int,input().split())

print(0 if N%K==0 else 1)

ABC118 A - B +/- A


解答例

a,b=map(int,input().split())

print(b-a if b%a>0 else a+b)


1.4 ビット演算


反転


サンプルコード

print(~(5-3))



実行結果

-3



サンプルコード

print(~-3)



実行結果

2



サンプルコード

print(~-4)



実行結果

3


ABC008 A - アルバム


解答例

print(~eval(input().replace(" ","-"))+2)


ABC069 A - K-City


解答例

a,b=map(int,input().split())

print(~-a*~-b)

ABC106 A - Garden


解答例

a,b=map(int,input().split())

print(~-a*~-b)


シフト

ABC104 A - Rated for Me


解答例

print(["ABC","ARC","AGC"][int(input())//50+8>>5])


ABC108 A - Pair


解答例

print(int(input())**2>>2)



1.5 代入演算


サンプルコード

a,b=1,2

print(a,b)


実行結果

1 2



サンプルコード

a,b=1,2

a,b=b,a
print(a,b)


実行結果

2 1


ABC006 B - トリボナッチ数列


解答例

a,b,c=0,0,1

for i in range(int(input())-1):
a,b,c=b,c,(a+b+c)%10007
print(a)

ABC079 B - Lucas Number


解答例

a,b=2,1

for i in range(int(input())):a,b=b,a+b
print(a)

ABC022 A - Best Body


解答例

n,s,t=map(int,input().split())

w=c=0
for i in range(n):
w+=int(input())
c+=s<=w<=t
print(c)


1.6 比較演算

ABC082 B - Two Anagrams


解答例

print("Yes" if sorted(input())<sorted(input())[::-1] else "No")


ABC024 A - 動物園


解答例

a,b,c,k=map(int,input().split())

s,t=map(int,input().split())
print(a*s+b*t-(s+t)*c*(s+t>=k))

ABC119 A - Still TBD


解答例

print("Heisei" if input()<="2019/04/30" else "TBD")



1.7 論理演算

ARC002 A - うるう年


解答例

Y=int(input())

print("YES" if Y%4==0 and Y%100!=0 or Y%400==0 else "NO")

ABC038 B - ディスプレイ


解答例

a,b=map(int,input().split())

c,d=map(int,input().split())
print("YES" if a==c or a==d or b==c or b==d else "NO")

ABC094 A - Cats and Dogs


解答例

a,b,x=map(int,input().split())

print("YES" if a<=x and x<=a+b else "NO")

ABC097 A - Colorful Transceivers


解答例

a,b,c,d=map(int,input().split())

print("Yes" if abs(c-a)<=d or abs(b-a)<=d and abs(c-b)<=d else "No")

ABC100 A - Happy Birthday!


解答例

a,b=map(int,input().split())

print("Yay!" if a<9 and b<9 else ":(")


1.8 条件式


if文

ARC002 A - うるう年


解答例

Y=int(input())

print("YES" if Y%4==0 and Y%100!=0 or Y%400==0 else "NO")

ABC016 B - A±B Problem


解答例

a,b,c=map(int,input().split())

print("?" if a+b==c and a-b==c else "+" if a+b==c else "-" if a-b==c else "!")

ABC031 B - 運動管理


解答例

l,w=map(int,input().split())

n=int(input())
for i in range(n):
a=int(input())
print(l-a if l>a else "0" if w>=a else "-1")

ABC059 B - Comparison


解答例

a=int(input())

b=int(input())
print("GREATER" if a>b else "LESS" if a<b else "EQUAL")

ABC020 A - クイズ


解答例

print("ABC" if input()=="1" else "chokudai")


ABC028 A - テスト評価


解答例

n=int(input())

print("Bad" if n<60 else "Good" if n<90 else "Great" if n<100 else "Perfect")

ABC030 A - 勝率計算


解答例

a,b,c,d=map(int,input().split())

T,A=b/a,d/c
print("TAKAHASHI" if T>A else "AOKI" if T<A else "DRAW")

ABC034 A - テスト


解答例

x,y=map(int,input().split())

print("Better" if x<y else "Worse")

ABC053 A - ABC/ARC


解答例

print("ABC" if int(input()) < 1200 else "ARC")


ABC056 A - HonestOrDishonest


解答例

a,b=input().split()

print("H" if a==b else "D")

ABC065 A - Expired?


解答例

x,a,b=map(int,input().split())

print("dangerous" if x<b-a else "safe" if a<b else "delicious")

ABC072 A - Sandglass2


解答例

x,t=map(int,input().split())

print("0" if x-t<0 else x-t)

ABC075 A - One out of Three


解答例

a,b,c=map(int,input().split())

print(a if b==c else b if a==c else c)

ABC078 A - HEX


解答例

x,y=input().split()

print("<" if x<y else "=" if x==y else ">")

ABC083 A - Libra


解答例

a,b,c,d=map(int,input().split())

print("Left" if a+b>c+d else "Balanced" if a+b==c+d else "Right")

ABC091 A - Two Coins


解答例

a,b,c=map(int,input().split())

print("Yes" if a+b>=c else "No")

ABC096 A - Day of Takahashi


解答例

a,b=map(int,input().split())

print(a-1 if a>b else a)

ABC099 A - ABD


解答例

print("ABC" if int(input())<1000 else "ABD")


ABC104 A - Rated for Me


解答例

r=int(input())

print("ABC" if r<1200 else "ARC" if r<2800 else "AGC")

ABC112 A - Programming Education


解答例

n=int(input())

print("Hello World" if n%2!=0 else int(input())+int(input()))

ABC122 A - Double Helix


解答例

b=input()

print("A" if b=="T" else "T" if b=="A" else "G" if b=="C" else "C")


if/break/else文

ARC010 A - 名刺交換


解答例

N,M,A,B=map(int,input().split())

for i in range(M):
if N<=A:N+=B
N-=int(input())
if N<0:
print(i+1)
break
else:print("complete")


if/in文


サンプルコード

List=["a","b","c"]

print("a" in List)


実行結果

True



サンプルコード

List=["a","b","c"]

print("a" not in List)


実行結果

False



サンプルコード

List=["a","b","c"]

print("d" in List)


実行結果

False



サンプルコード

List=["a","b","c"]

print("d" not in List)


実行結果

True



サンプルコード

List=["a","b","c"]

print("a" in "auieo")


実行結果

True


ABC033 C - 数式の書き換え


解答例

S=map(str,input().split("+"))

ans=0
for s in S:
if "0" not in s:ans+=1
print(ans)

ABC029 B - カキ


解答例

print(sum("r" in input() for i in range(12)))


ABC089 B - Hina Arare


解答例

input()

l=map(str,input().split())
print("Three" if len(set(l))==3 else "Four")


解答例

input()

print("Four" if "Y" in input() else "Three")

ABC103 B - String Rotation


解答例

print("Yes" if input() in input()*2 else "No")


ABC122 B - ATCoder


解答例

S=input()

m=0
count=0
for s in S:
if s in "A":count+=1
elif s in "C":count+=1
elif s in "G":count+=1
elif s in "T":count+=1
else:count=0
m=max(m,count)
print(m)

ABC006 A - 世界のFizzBuzz


解答例

print("YES" if input() in "369" else "NO")


ABC049 A - 居合を終え、青い絵を覆う / UOIAUAI


解答例

print("vowel" if input() in "aiueo" else "consonant")


ABC073 A - September 9


解答例

print("Yes" if "9" in input() else "No")


ABC109 A - ABC333


解答例

print("No" if "2" in input() else "Yes")


ABC114 A - 753


解答例

print("YES" if input() in "753" else "NO")



複数条件式

ABC061 A - Between Two Integers


解答例

a,b,c=map(int,input().split())

print("Yes" if a<=c<=b else "No")

ABC079 A - Good Integer


解答例

a,b,c,d=input()

print("Yes" if a==b==c or b==c==d else "No")

ABC079 A - Good Integer


解答例

a,b,c,d=input()

print("Yes" if a==b==c or b==c==d else "No")

ABC094 A - Cats and Dogs


解答例

a,b,x=map(int,input().split())

print("YES" if a<=x<=a+b else "NO")


解答例

a,b,x=map(int,input().split())

print("YES" if 0<=x-a<=b else "NO")


1.9 繰り返し文


while文

ABC045 B - 3人でカードゲームイージー / Card Game for Three (ABC Edit)


解答例

S={c:list(input()) for c in "abc"}

s="a"
while S[s]:s=S[s].pop(0)
print(s.upper())

ABC065 B - Trained?


解答例

n=int(input())

a=[int(input()) for i in range(n)]
c,s=1,a[0]
while s!=2 and c<n:c,s=c+1,a[s-1]
print(c if c<n else -1)

ABC066 B - ss


解答例

s=list(input())

while len(s)!=0:
s.pop()
if len(s)%2==0 and s[:len(s)//2]==s[len(s)//2:]:
print(len(s))
exit()

ABC081 B - Shift only


解答例

input()

A=list(map(int,input().split()))
ans=0
while all(a%2==0 for a in A):
A=[a/2 for a in A]
ans+=1
print(ans)

ABC116 B - Collatz Problem


解答例

S=int(input())

l=[]
while (S not in l):
l.append(S)
if S%2==0:S//=2
else:S=3*S+1
print(len(l)+1)

ABC032 A - 高橋君と青木君の好きな数


解答例

a,b,n=[int(input()) for i in range(3)]

while n%a!=0 or n%b!=0:n+=1
print(n)


第2章 データ型観点


2.1 整数(int)


サンプルコード

print(int(2.9))



実行結果

2



2.2 浮動小数点(float)


サンプルコード

print(5e10)



実行結果

50000000000.0



サンプルコード

print(1.1e-3)



実行結果

0.0011


ABC119 B - Digital Gifts


解答例

N=int(input())

ans=0
for i in range(N):
x,u=input().split()
if u=="BTC":ans+=float(x)*380000
else:ans+=int(x)
print(ans)

ARC018 A - BMI


解答例

H,B=map(float,input().split())

print(H**2*B/1e4)


2.3 文字列(str)


文字列の結合


サンプルコード

print("foo"+"bar")



実行結果

foobar


ABC020 B - 足し算


解答例

a,b=input().split()

print(2*int(a+b))

ABC010 A - ハンドルネーム


解答例

print(input()+"pp")


ABC029 A - 複数形


解答例

print(input()+"s")


ABC068 A - ABCxxx


解答例

print("ABC"+input())


ABC090 A - Diagonal String

print(input()[0]+input()[1]+input()[2])

a=input()[0]

b=input()[1]
c=input()[2]
print(a+b+c)

ABC111 A - AtCoder Beginner Contest 999


解答例

print("".join(["9" if x=="1" else "1" for x in input()]))



文字列の参照


サンプルコード

String="abc"

print(String[0],String[1],String[2])


実行結果

a b c



サンプルコード

String="abc"

print(String[-1],String[-2],String[-3])


実行結果

c b a


ABC069 B - i18n


解答例

s=input()

print(s[0]+str((len(s)-2))+s[-1])

ABC025 A - 25個の文字列


解答例

s=input()

n=int(input())-1
print(s[n//5]+s[n%5])

ABC038 A - お茶


解答例

print("YES" if input()[-1]=="T" else "NO")


ABC048 A - AtCoder *** Contest


解答例

print("A%sC"%input()[8])



解答例

print("A"+input()[8]+"C")


ABC059 A - Three-letter acronym


解答例

a,b,c=input().split()

print((a[0]+b[0]+c[0]).upper())

ABC060 A - Shiritori


解答例

a,b,c=input().split()

print("YES" if a[-1]==b[0] and b[-1]==c[0] else "NO")

ABC062 A - Grouping


解答例

S="XACABABAABABA"

x,y=map(int,input().split())
print("Yes" if S[x]==S[y] else "No")

ABC070 A - Palindromic Number


解答例

n=input()

print("Yes" if n[0]==n[2] else "No")

ABC079 A - Good Integer


解答例

n=input()

print("Yes" if n[0]==n[1]==n[2] or n[1]==n[2]==n[3] else "No")

ABC090 A - Diagonal String

print(input()[0]+input()[1]+input()[2])

a=input()[0]

b=input()[1]
c=input()[2]
print(a+b+c)


文字列の逆順


サンプルコード

String="abc"

print(String[::-1])


実行結果

cba


ABC090 B - Palindromic Numbers


解答例

a,b=map(int,input().split())

print(sum(i==i[::-1] for i in map(str,range(a,b+1))))


解答例

a,b=map(int,input().split())

print(len([i for i in map(str,range(a,b+1)) if i==i[::-1]]))

ABC012 A - スワップ


解答例

print(*input().split()[::-1])


ABC070 A - Palindromic Number


解答例

n=input()

print("Yes" if n==n[::-1] else "No")

ABC077 A - Rotation


解答例

print("YES" if input()==input()[::-1] else "NO")



文字列の比較

ABC046 B - 文字列大好きいろはちゃんイージー / Iroha Loves Strings (ABC Edition)


解答例

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

s=sorted([input() for i in range(n)])
print(*s,sep="")


解答例

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

s=sorted([input() for i in range(n)])
print("".join(s))

ABC082 B - Two Anagrams


解答例

print("Yes" if sorted(input())<sorted(input())[::-1] else "No")


ABC119 A - Still TBD


解答例

print("Heisei" if input()<="2019/04/30" else "TBD")



文字列の判定


サンプルコード

String="abc"

[print(chr(i), end=" ") for i in range(ord('a'), ord('z')+1) if chr(i) in String]


実行結果

a b c



サンプルコード

[print(chr(i), end=" ") for i in range(ord('a'), ord('z')+1) if chr(i) not in String]



実行結果

d e f g h i j k l m n o p q r s t u v w x y z


ABC071 B - Not Found


解答例

print(min(set(map(chr,range(97,123)))-set(input())or["None"]))



解答例

letters="abcdefghijklmnopqrstuvwxyz"

ans=sorted(set(letters)^set(input()))
print("None" if len(ans)==0 else ans[0])

ABC090 B - Palindromic Numbers


解答例

a,b=map(int,input().split())

print(sum(i==i[::-1] for i in map(str,range(a,b+1))))


解答例

a,b=map(int,input().split())

print(len([i for i in map(str,range(a,b+1)) if i==i[::-1]]))

ABC078 A - HEX


解答例

x,y=input().split()

print("<" if x<y else "=" if x==y else ">")


文字列のコピー

ABC018 B - 文字列の反転


解答例

s=input()

for i in range(int(input())):
l,r=map(int,input().split())
s=s[:l-1]+s[l-1:r][::-1]+s[r:]
print(s)

ABC043 B - バイナリハックイージー / Unhappy Hacking (ABC Edit)


解答例

t=""

for x in input():
if x=="B":t=t[:-1]
else:t+=x
print(t)

ABC066 B - ss


解答例

s=input()[:-1]

while s[:len(s)//2]!=s[len(s)//2:]:s=s[:-1]
print(len(s))


大文字小文字変換


  • upper:すべての文字列を大文字に変換する


サンプルコード

Text="this is a pen."

print(Text.upper())


実行結果

THIS IS A PEN.


ABC011 B - 名前の確認


解答例

s=input()

print(s[0].upper()+s[1:].lower())

ABC059 A - Three-letter acronym


解答例

for a in input().upper().split():print(a[0],end="")



解答例

a,b,c=input().split()

print((a[0]+b[0]+c[0]).upper())


  • lower:すべての文字列を小文字に変換する


サンプルコード

Text="THIS IS A PEN."

print(Text.lower())


実行結果

this is a pen.


ABC011 B - 名前の確認


解答例

s=input()

print(s[0].upper()+s[1:].lower())


  • capitalize:文字列の先頭文字を大文字に変換する


サンプルコード

Text="this is a pen."

print(Text.capitalize())


実行結果

This is a pen.


ABC011 B - 名前の確認


解答例

print("abcd".capitalize())



  • title:各単語の先頭文字を大文字に変換する


サンプルコード

Text="this is a pen."

print(Text.title())


実行結果

This Is A Pen.



大文字小文字判定

ABC104 B - AcCepted


解答例

s=input()

print("AC" if "C" in s[2:-1] and "A" in s and s[1:].replace("C","",1).islower() else "WA")


2.4 リスト(list)


  • リスト[ ]はミュータブルで要素の挿入と削除を行うことができ、インデックス(番号)で要素にアクセスします。


要素の追加


  • append/extend/insert


サンプルコード

List=["a","b","c"]

List.append('d')
print(List)


実行結果

['a', 'b', 'c', 'd']



サンプルコード

List=["a","b","c"]

List.extend(['d','e'])
print(List)


実行結果

['a', 'b', 'c', 'd', 'e']



サンプルコード

List=["a","b","c"]

List.insert(1,'z')
print(List)


実行結果

['a', 'z', 'b', 'c']



サンプルコード

List=["a","b","c"]

List.append(['d','e'])
print(List)


実行結果

['a', 'b', 'c', ['d', 'e']]



サンプルコード

List=["a","b","c"]

List.insert(1,['x','y'])
print(List)


実行結果

['a', ['x', 'y'], 'b', 'c']


ARC049 A - "強調"


解答例

S=list(input())

A,B,C,D=map(int,input().split())
S.insert(D,"\"")
S.insert(C,"\"")
S.insert(B,"\"")
S.insert(A,"\"")
print(*S,sep="")


要素の探索


  • index


サンプルコード

List=["a","b","c","d","e","f"]

print(List.index('c'))


実行結果

2



サンプルコード

List=["a","b","c","d","c","c"]

print(List.index('c'))


実行結果

2


ARC003 A - GPA計算


解答例

print((1/int(input()))*sum("FDCBA".index(r) for r in input()))



解答例

N=int(input())

print(sum(map(int,input().translate(str.maketrans("FDCBA","01234"))))/N)

ARC053 B - A to Z String


解答例

s=input()

print(len(s)-s[::-1].index("Z")-s.index("A"))

ABC033 B - 町の合併


解答例

n=int(input())

S=[]
P=[]
for i in range(n):
s,p=input().split()
S.append(s)
P.append(int(p))
if max(P)>sum(P)/2:print(S[P.index(max(P))])
else:print("atcoder")

ABC113 B - Palace


解答例

n=int(input())

t,a=map(int,input().split())
h=list(map(int,input().split()))
z=[abs(t-x*0.006-a) for x in h]
print(z.index(min(z))+1)

ABC013 A - A


解答例

print('0ABCDE'.index(input()))



解答例

print(["A","B","C","D","E"].index(input())+1)


ABC018 A - 豆まき


解答例

X=[int(input()) for i in range(3)]

for x in X:print(3-sorted(X).index(x))


解答例

l=[int(input()) for _ in range(3)]

s=sorted(l)[::-1]
for i in l:
print(s.index(i)+1)


要素の削除


  • pop/remove/del


サンプルコード

List=["a","b","c","d","e","f"]

print(List.pop(1))
print(List)


実行結果

b

['a', 'c', 'd', 'e', 'f']


サンプルコード

List=["a","b","c","d","e","f"]

List.remove('d')
print(List)


実行結果

['a', 'b', 'c', 'e', 'f']



サンプルコード

List=["a","b","c","d","e","f"]

del List[1]
print(List)


実行結果

['a', 'c', 'd', 'e', 'f']


ABC045 B - 3人でカードゲームイージー / Card Game for Three (ABC Edit)


解答例

S={c:list(input()) for c in "abc"}

s="a"
while S[s]:s=S[s].pop(0)
print(s.upper())


要素の出現回数


  • count


サンプルコード

List=["a","b","b","c","c","c"]

print(List.count('c'))


実行結果

3



サンプルコード

List=["a","b","b","c","c","c"]

print(List.count('d'))


実行結果

0


ARC001 A - センター採点


解答例

input()

C=input()
print(*sorted(C.count(c) for c in "1234")[::-3])


解答例

input()

C=input()
l=[C.count(c) for c in "1234"]
print(max(l),min(l))


解答例

input()

C=input()
a=C.count("1")
b=C.count("2")
c=C.count("3")
d=C.count("4")
print(max(a,b,c,d),min(a,b,c,d))

ABC015 B - 高橋くんの集計


解答例

n=int(input())

a=list(map(int,input().split()))
print(-(-sum(a)//(n-a.count(0))))

ABC028 B - 文字数カウント


解答例

s=input()

print(s.count("A"),s.count("B"),s.count("C"),s.count("D"),s.count("E"),s.count("F"))

ABC044 B - 美しい文字列 / Beautiful Strings


解答例

s=input()

print("Yes" if all([s.count(i)%2==0 for i in set(s)]) else "No")

ABC091 B - Two Colors Card Game


解答例

n=[input() for _ in range(int(input()))]

m=[input() for _ in range(int(input()))]
l=list(set(n))
print(max(0,max(n.count(l[i])-m.count(l[i]) for i in range(len(l)))))

ABC042 A - 和風いろはちゃんイージー / Iroha and Haiku (ABC Edition)


解答例

n=input().split()

print("YES" if n.count("5")==2 and n.count("7")==1 else "NO")

ABC084 B - Postal Code


解答例

a,b=map(int,input().split())

s=input()
print("Yes" if s[a]=="-" and s.count("-")==1 else "No")

ABC081 A - Placing Marbles


解答例

print(input().count("1"))


ABC095 A - Something on It


解答例

print(700+100*input().count("o"))


ABC101 A - Eating Symbols Easy


解答例

print(2*input().count('+')-4)



解答例

s=list(input())

print(s.count('+')-s.count('-'))


要素の連結


  • join


サンプルコード

List=["ab","cd","ef"]

print(''.join(List))


実行結果

abcdef


ARC045 A - スペース高橋君


解答例

S=list(input().split())

a=[]
for s in S:
if s=="Left":a.append("<")
elif s=="Right":a.append(">")
else:a.append("A")
print(" ".join(a))


要素のユニーク化


  • set


サンプルコード

List=[2,3,1,2]

print(list(set(List)))


実行結果

[1, 2, 3]



サンプルコード

List=[[1,0],[0,0],[1,1],[1,0],[0,1],[0,0]]

print(list(map(list,set(map(tuple,List)))))


実行結果

[[0, 1], [1, 0], [0, 0], [1, 1]]


ABC009 B - 心配性な富豪、ファミリーレストランに行く。


解答例

n=int(input())

print(sorted(set([int(input()) for i in range(n)]))[-2])

ABC032 B - 高橋君とパスワード


解答例

s=input()

k=int(input())
print(len(set(s[i:i+k] for i in range(len(s)-k+1))))

ABC063 B - Varied


解答例

s=input()

print("no" if len(s)-len(set(s)) else "yes")

ABC085 B - Kagami Mochi


解答例

print(len(set([int(input()) for _ in range(int(input()))])))


ABC033 A - 暗証番号


解答例

print("DIFFERENT" if len(set(input()))!=1 else "SAME")


ABC046 A - AtCoDeerくんとペンキ / AtCoDeer and Paint Cans


解答例

print(len(set(input().split())))


ABC093 A - abc of ABC


解答例

print("Yes" if len(set(input()))==3 else "No")



スライス


サンプルコード

List=["a","b","c","d","e"]

print(List[1:3])


実行結果

['b', 'c']



サンプルコード

List=["a","b","c","d","e"]

print(List[1:4:2])


実行結果

['b', 'd']



サンプルコード

List=["a","b","c","d","e"]

print(List[:3])

```text:実行結果
['a', 'b', 'c']



サンプルコード

List=["a","b","c","d","e"]

print(List[3:])


実行結果

['d', 'e']



サンプルコード

List=["a","b","c","d","e"]

print(List[:-3])


実行結果

['a', 'b']



サンプルコード

List=["a","b","c","d","e"]

print(List[-3:])


実行結果

['c', 'd', 'e']



サンプルコード

List=["a","b","c","d","e"]

print(List[::-1])


実行結果

['e', 'd', 'c', 'b', 'a']



サンプルコード

List=["a","b","c","d","e"]

print(List[::-2])


実行結果

['e', 'c', 'a']


ARC005 A - 大好き高橋君


解答例

input()

print(input()[:-1].lower().split().count("takahashikun"))

ARC049 A - "強調"


解答例

S=input()

A,B,C,D=map(int,input().split())
print(S[:A]+'"'+S[A:B]+'"'+S[B:C]+'"'+S[C:D]+'"'+S[D:])

ABC122 C - GeT AC


解答例

N,Q=map(int,input().split())

S=input()
count=[0]*N
for i in range(1,N):
count[i]+=count[i-1]
if S[i-1:i+1]=="AC":count[i]+=1
for i in range(Q):
l,r=map(int,input().split())
print(count[r-1]-count[l-1])

ABC011 B - 名前の確認


解答例

s=input()

print(s[0].upper()+s[1:].lower())

ABC026 B - N重丸


解答例

r=sorted(int(input())**2 for i in range(int(input())))[::-1]

print((sum(r[::2])-sum(r[1::2]))*355/113)

ABC032 B - 高橋君とパスワード


解答例

s=input()

k=int(input())
print(len(set(s[i:i+k] for i in range(len(s)-k+1))))

ABC066 B - ss


解答例

s=input()[:-1]

while s[:len(s)//2]!=s[len(s)//2:]:s=s[:-1]
print(len(s))


解答例

s=list(input())

while len(s)!=0:
s.pop()
if len(s)%2==0 and s[:len(s)//2]==s[len(s)//2:]:
print(len(s))
exit()

ABC067 B - Snake Toy


解答例

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

print(sum(sorted(map(int,input().split()))[-k:]))


解答例

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

print(sum(sorted(map(int,input().split()))[::-1][:k]))

ABC072 B - OddString


解答例

print(input()[::2])


ABC088 B - Card Game for Two


解答例

input()

l=sorted(map(int,input().split()))[::-1]
print(sum(l[::2])-sum(l[1::2]))

ABC093 B - Small and Large Integers


解答例

a,b,k=map(int,input().split())

r=range(a,b+1)
for i in sorted(set(r[:k])|set(r[-k:])):print(i)

ABC098 B - Cut and Count


解答例

n=int(input())

s=input()
print(max(len(set(s[:i])&set(s[i:])) for i in range(n)))

ABC114 B - 754


解答例

s=input()

print(min(abs(int(s[i:i+3])-753) for i in range(len(s))))

ABC115 B - Christmas Eve Eve


解答例

n=int(input())

p=sorted([int(input()) for i in range(n)])
print(p[-1]//2+sum(p[:-1]))

ABC117 B - Polygon


解答例

input()

L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")

ABC064 A - RGB Cards


解答例

print("NO" if int(input()[::2])%4 else "YES")


ABC066 A - ringring


解答例

print(sum(sorted(map(int,input().split()))[:2]))


ABC085 A - Already 2018


解答例

print("2018"+input()[4:])



リスト内包表記


  • 非ネスト


サンプルコード

List=[i for i in range(5)]

print(List)


実行結果

[0, 1, 2, 3, 4]



サンプルコード

A=[2,4,6,8,10]

A=[a//2 for a in A]
print(A)


実行結果

[1, 2, 3, 4, 5]


ABC081 B - Shift only


解答例

input()

A=list(map(int,input().split()))
ans=0
while all(a%2==0 for a in A):
A=[a/2 for a in A]
ans+=1
print(ans)


  • ネスト


サンプルコード

List=[1*i + 10*j + 100*k for k in range(2) for j in range(3) for i in range(4)]

print(List)


実行結果

[0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 100, 101, 102, 103, 110, 111, 112, 113, 120, 121, 122, 123]


ABC051 B - Sum of Three Integers


解答例

k,s=map(int,input().split())

print(len([1 for z in range(k+1) for y in range(k+1) if 0<=s-y-z<=k]))


解答例(TLE)

k,s=map(int,input().split())

print([x+y+z for z in range(k+1) for y in range(k+1) for x in range(k+1)].count(s))

ABC087 B - Coins


解答例

a,b,c,x=[int(input()) for _ in range(4)]

print([500*x+100*y+50*z for z in range(c+1) for y in range(b+1) for x in range(a+1)].count(x))

ABC105 B - Cakes and Donuts


解答例

print("Yes" if [4*x+7*y for y in range(101) for x in range(101)].count(int(input())) else "No")



2.5 タプル(tuple)


  • タプル( )はイミュータブルで要素の書き換えができません。リストと同様、インデックス(番号)で要素にアクセスします。


要素の探索

ABC054 C - One-stroke Path


解答例

import itertools

N,M=map(int,input().split())
edges={tuple(sorted(map(int,input().split()))) for i in range(M)}
ans=0
for i in itertools.permutations(range(2,N+1),N-1):
l=[1]+list(i)
ans+=sum(1 for edge in zip(l,l[1:]) if tuple(sorted(edge)) in edges)==N-1
print(ans)


2.6 辞書(dict)


  • 辞書{ }はミュータブルでリストに似ていますが、要素へのアクセスは値に一意なキーで行います。


要素の探索

ARC012 A - 週末


解答例

print({'Mo':5,'Tu':4,'We':3,'Th':2,'Fr':1,'Sa':0,'Su':0}[input()[:2]])



解答例

d=({"Saturday":0,"Sunday":0,"Monday":5,"Tuesday":4,"Wednesday":3,"Thursday":2,"Friday":1})

print(d[input()])

ABC036 C - 座圧


解答例

N=int(input())

A=[int(input()) for i in range(N)]
B={a:i for (i,a) in enumerate(sorted(set(A)))}
for a in A:
print(B[a])


解答例

import bisect

N=int(input())
A=[int(input()) for i in range(N)]
B=sorted(list(set(A)))
for a in A:
print(bisect.bisect_left(B,a))

ABC045 B - 3人でカードゲームイージー / Card Game for Three (ABC Edit)


解答例

S={c:list(input()) for c in "abc"}

s="a"
while S[s]:s=S[s].pop(0)
print(s.upper())

ABC119 B - Digital Gifts


解答例

XU=[input().split() for i in range(int(input()))]

print(sum([float(x)*{"JPY":1,"BTC":380000}[u] for x,u in XU]))


2.7 集合(set)


  • 集合{ }は辞書と同様、要素へのアクセスは値に一意なキーで行いますが同じ要素を一つしか持てないため辞書のように値はありません。


A \cup B


サンプルコード

print({"a","b","c"}|{"c","d","e"})



実行結果

{'a', 'b', 'd', 'e', 'c'}


ABC093 B - Small and Large Integers


解答例

a,b,k=map(int,input().split())

r=range(a,b+1)
for i in sorted(set(r[:k])|set(r[-k:])):print(i)


A - B


サンプルコード

print({"a","b","c"}-{"c","d","e"})



実行結果

{'a', 'b'}



A \cap B


サンプルコード

print({"a","b","c"}&{"c","d","e"})



実行結果

{'c'}


ABC079 C - Cat Snuke and a Voyage


解答例

N,M=map(int,input().split())

sa=set()
sb=set()
for i in range(M):
a,b=map(int,input().split())
if a==1:sb.add(b)
if b==N:sa.add(a)
print("IMPOSSIBLE" if len(sa&sb)==0 else "POSSIBLE")

ABC098 B - Cut and Count


解答例

n=int(input())

s=input()
print(max(len(set(s[:i])&set(s[i:])) for i in range(n)))

ABC118 B - Foods Loved by Everyone


解答例

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

S=set(range(1,m+1))
for i in range(n):
K,*A=map(int,input().split())
S&=set(A)
print(len(S))


対称差

A ⊕ B


サンプルコード

print({"a","b","c"}^{"c","d","e"})



実行結果

{'a', 'b', 'e', 'd'}


ABC073 C - Write and Erase


解答例

N=int(input())

s=set()
for i in range(N):s^={input()}
print(len(s))

ABC027 A - 長方形


解答例

print(eval(input().replace(' ','^')))


ABC075 A - One out of Three


解答例

print(eval(input().replace(" ","^")))



部分集合

A \subseteq B


サンプルコード

print({"a","b"}<={"a","b","c"})



実行結果

True



サンプルコード

print({"a","d"}<={"a","b","c"})



実行結果

False


ABC062 A - Grouping


解答例

x,y=input().split()

a={"1","3","5","7","8","10","12"}
b={"4","6","9","11"}
print("Yes" if {x,y}<=a or {x,y}<=b else "No")


文字の集合


サンプルコード

import string

letters=string.ascii_lowercase
print(letters)


実行結果

abcdefghijklmnopqrstuvwxyz



サンプルコード

print(sorted(map(chr,range(97,123))))



実行結果

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']



サンプルコード

print(sorted(map(chr,range(65,91))))



実行結果

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']


ABC071 B - Not Found


解答例

print(min(set(map(chr,range(97,123)))-set(input())or["None"]))


ABC093 B - Small and Large Integers


解答例

a,b,k=map(int,input().split())

r=range(a,b+1)
for i in sorted(set(r[:3])|set(r[-3:])):
print(i)


2.8 ブール(bool)


ビット変換


サンプルコード

print(True+0)



実行結果

1



サンプルコード

print(False+0)



実行結果

0



サンプルコード

print(-(3>2))



実行結果

-1



サンプルコード

print(-(3<2))



実行結果

0


ABC029 B - カキ


解答例

print(sum("r" in input() for i in range(12)))


ABC022 A - Best Body


解答例

n,s,t=map(int,input().split())

w=c=0
for i in range(n):
w+=int(input())
c+=s<=w<=t
print(c)

ABC024 A - 動物園


解答例

a,b,c,k=map(int,input().split())

s,t=map(int,input().split())
print(a*s+b*t-(s+t)*c*(s+t>=k))

ABC096 A - Day of Takahashi


解答例

a,b=map(int,input().split())

print(a-(a>b))

ABC105 A - AtCoder Crackers


解答例

print((eval(input().replace(" ","%"))>0)+0)



2.9 進数変換(bin/oct/hex)


  • 2進数⇒10進数


サンプルコード

print(int("1101",2))



実行結果

13



  • 8進数⇒10進数


サンプルコード

print(int("700",8))



実行結果

448



  • 16進数⇒10進数


サンプルコード

print(int("FE",16))



実行結果

254



  • 10進数⇒2進数


サンプルコード

print(bin(23))



実行結果

0b10111



  • 10進数⇒8進数


サンプルコード

print(oct(23))



実行結果

0o27



  • 10進数⇒16進数


サンプルコード

print(hex(23))



実行結果

0x17



  • 2進数表示


サンプルコード

print(0b10111)



実行結果

23



  • 8進数表示


サンプルコード

print(0o27)



実行結果

23



  • 16進数表示


サンプルコード

print(0x17)



実行結果

23


ABC105 C - Base -2 Number


解答例

n=int(input())

x=""
while n!=0:
x=str(n%2)+x
n=-(n//2)
print(0 if x=="" else x)

ABC068 B - Break Number


解答例

print(2**(len(bin(int(input())))-3))



第3章 データ構造観点


3.1 スタック


  • スタック:Stack(LIFO)


サンプルコード

stack=[3,4,5]

stack.append(6)
print(stack)
stack.pop()
print(stack)


実行結果

[3, 4, 5, 6]

[3, 4, 5]


サンプルコード

stack=["a","b","c"]

stack.pop()
print(stack)
stack.append("d")
print(stack)


実行結果

['a', 'b']

['a', 'b', 'd']


サンプルコード

import queue

q=queue.LifoQueue()
List=[3,4,5]
for l in List:q.put(l)
while not q.empty():print(q.get())


実行結果

5

4
3

ABC120 C - Unification


解答例

S=input()

stack=[]
count=0
for s in S:
if not stack:
stack.append(s)
elif stack[-1]!=s:
stack.pop()
count+=2
else:
stack.append(s)
print(count)

ABC043 B - バイナリハックイージー / Unhappy Hacking (ABC Edit)


解答例

t=""

for x in input():
if x=="B":t=t[:-1]
else:t+=x
print(t)


解答例

t=[]

for x in input():
if x=="B":
try:t.pop()
except:pass
else:t.append(x)
print("".join(t))


3.2 キュー


  • キュー:Queue(FIFO)


サンプルコード

queue=[3,4,5]

queue.append(6)
print(queue)
queue.pop(0)
print(queue)


実行結果

[3, 4, 5, 6]

[4, 5, 6]


サンプルコード

queue=["a","b","c"]

queue.pop(0)
print(queue)
queue.append("d")
print(queue)


実行結果

['b', 'c']

['b', 'c', 'd']


サンプルコード

from collections import deque

queue=deque(["a","b","c"])
queue.append("d")
print(queue)
queue.popleft()
print(queue)


実行結果

deque(['a', 'b', 'c', 'd'])

deque(['b', 'c', 'd'])


サンプルコード

import queue

q=queue.Queue()
List=[3,4,5]
for l in List:q.put(l)
while not q.empty():print(q.get())


実行結果

3

4
5

ABC077 C - pushpush


解答例

N=int(input())

A=list(map(int,input().split()))
print(*A[::-2],*A[N%2::2])


解答例(TLE)

N=int(input())

A=list(map(int,input().split()))
B=[]
for i in range(N):
B.append(A[i])
B=B[::-1]
print(*B)

ABC045 B - 3人でカードゲームイージー / Card Game for Three (ABC Edit)


解答例

S={c:list(input()) for c in "abc"}

s="a"
while S[s]:s=S[s].pop(0)
print(s.upper())


第4章 基本処理観点


4.1 長さ


文字列


サンプルコード

print(len("aiueo"))



実行結果

5



サンプルコード

print(max("foo","hoge",key=len))



実行結果

hoge


ABC069 B - i18n


解答例

s=input()

print(s[0]+str((len(s)-2))+s[-1])

ABC015 A - 高橋くんの研修


解答例

print(max(input(),input(),key=len))



リスト

ABC063 B - Varied


解答例

s=input()

print("no" if len(s)-len(set(s)) else "yes")

ABC033 A - 暗証番号


解答例

print("DIFFERENT" if len(set(input()))!=1 else "SAME")


ABC046 A - AtCoDeerくんとペンキ / AtCoDeer and Paint Cans


解答例

print(len(set(input().split())))


ABC093 A - abc of ABC


解答例

print("Yes" if len(set(input()))==3 else "No")



4.2 ソート


昇順


  • 1次元リスト


サンプルコード

List=[2,1,3]

List.sort()
print(List)


実行結果

[1, 2, 3]



  • 2次元リスト


サンプルコード

List=[[0,1],[1,1],[1,0],[0,0]]

List.sort(key=lambda List:(List[0],List[1]))
print(List)


実行結果

[[0, 0], [0, 1], [1, 0], [1, 1]]


ABC009 B - 心配性な富豪、ファミリーレストランに行く。


解答例

n=int(input())

print(sorted(set([int(input()) for i in range(n)]))[-2])

ABC026 B - N重丸


解答例

r=sorted(int(input())**2 for i in range(int(input())))[::-1]

print((sum(r[::2])-sum(r[1::2]))*355/113)

ABC046 B - 文字列大好きいろはちゃんイージー / Iroha Loves Strings (ABC Edition)

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

s=sorted([input() for i in range(n)])
print(*s,sep="")

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

s=sorted([input() for i in range(n)])
print("".join(s))

ABC064 B - Traveling AtCoDeer Problem


解答例

input()

l=sorted(map(int,input().split()))
print(l[-1]-l[0])

ABC067 B - Snake Toy


解答例

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

print(sum(sorted(map(int,input().split()))[-k:]))


解答例

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

print(sum(sorted(map(int,input().split()))[::-1][:k]))

ABC102 B - Maximum Difference


解答例

input()

a=sorted(map(int,input().split()))
print(a[-1]-a[0])

ABC018 A - 豆まき


解答例

X=[int(input()) for i in range(3)]

for x in X:print(3-sorted(X).index(x))

ABC019 A - 高橋くんと年齢


解答例

print(sorted(map(int,input().split()))[1])


ABC047 A - キャンディーと2人の子供 / Fighting over Candies


解答例

a,b,c=sorted(map(int,input().split()))

print("Yes" if a+b==c else "No")


解答例

l=sorted(map(int,input().split()))

print("Yes" if sum(l[:2])==l[2] else "No")

ABC066 A - ringring


解答例

a,b,c=sorted(map(int,input().split()))

print(a+b)

ABC103 A - Task Scheduling Problem


解答例

a,b,c=sorted(map(int,input().split()))

print(c-a)

ABC110 A - Maximize the Formula


解答例

print(eval('+'.join(sorted(input()))+'*10'))



解答例

A,B,C=sorted(map(int,input().split()))

print(10*C+B+A)


降順


  • 1次元リスト


サンプルコード

List=[2,1,3]

List.sort(reverse=True)
print(List)


実行結果

[3, 2, 1]



  • 2次元リスト


サンプルコード

List=[[0,1],[1,1],[1,0],[0,0]]

List.sort(key=lambda List:(List[0],List[1]),reverse=True)
print(List)


実行結果

[[1, 1], [1, 0], [0, 1], [0, 0]]


ARC042 A - 掲示板


解答例

N,M=map(int,input().split())

A=[int(input()) for i in range(M)][::-1]
ans=[]
s=set()
for a in A:
if a not in s:ans.append(a)
s.add(a)
for i in range(1,N+1):
if i not in s:ans.append(i)
print(*ans,sep="\n")

ABC117 B - Polygon


解答例

input()

L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")

ABC018 A - 豆まき


解答例

l=[int(input()) for _ in range(3)]

s=sorted(l)[::-1]
for i in l:
print(s.index(i)+1)


4.3 最大値 / 最小値


最大値


サンプルコード

print(max(1,2))



実行結果

2



サンプルコード

print(max(2,1,3))



実行結果

3



サンプルコード

print(max([2,1,3]))



実行結果

3



サンプルコード

print(max(['b','a','c','d']))



実行結果

d



サンプルコード

print(max(['ab','aa','ca','bd']))



実行結果

ca



サンプルコード

print(max(['a','bcde','fg','hij'],key=len))



実行結果

bcde


ABC052 B - Increment Decrement


解答例

input()

s=input()
c,m=0,0
for i in range(len(s)):
if s[i]=="I":
c+=1
m=max(c,m)
if s[i]=="D":
c=c-1
m=max(c,m)
print(m)

ABC056 B - NarrowRectanglesEasy


解答例

w,a,b=map(int,input().split())

print(max(abs(a-b)-w,0))

ABC064 B - Traveling AtCoDeer Problem


解答例

input()

a=list(map(int,input().split()))
print(max(a)-min(a))

ABC115 B - Christmas Eve Eve


解答例

l=[int(input()) for _ in range(int(input()))]

print(sum(l)-int(max(l)/2))

ABC002 A - 正直者


解答例

print(max(map(int,input().split())))


ABC015 A - 高橋くんの研修


解答例

print(max(input(),input(),key=len))


ABC037 A - 饅頭


解答例

a,b,c=map(int,input().split())

print(max(c//a,c//b))

ABC044 A - 高橋君とホテルイージー / Tak and Hotels (ABC Edit)


解答例

n,k,x,y=[int(input()) for i in range(4)]

print(n*x-(x-y)*max(n-k,0))

ABC052 A - Two Rectangles


解答例

a,b,c,d=map(int,input().split())

print(max(a*b,c*d))

ABC098 A - Add Sub Mul


解答例

a,b=map(int,input().split())

print(max(a+b,a-b,a*b))

ABC100 A - Happy Birthday!


解答例

print("Yay!" if max(map(int,input().split()))<9 else ":(")


ABC103 A - Task Scheduling Problem


解答例

A=list(map(int,input().split()))

print(max(A)-min(A))

ABC117 B - Polygon


解答例

input()

L=list(map(int,input().split()))
print("Yes" if sum(L)>2*max(L) else "No")


最小値


サンプルコード

print(min(1,2))



実行結果

1



サンプルコード

print(min(2,1,3))



実行結果

1



サンプルコード

print(min([2,1,3]))



実行結果

1



サンプルコード

print(min(['b','a','c','d']))



実行結果

a



サンプルコード

print(min(['ab','aa','ca','bd']))



実行結果

aa



サンプルコード

print(min(['a','bcde','fg','hij'],key=len))

#


実行結果

a


ABC005 B - おいしいたこ焼きの食べ方


解答例

n=int(input())

print(min(int(input()) for i in range(n)))

ABC013 B - 錠


解答例

x=abs(int(input())-int(input()))

print(min(x,10-x))

ABC064 B - Traveling AtCoDeer Problem


解答例

input()

a=list(map(int,input().split()))
print(max(a)-min(a))

ABC076 B - Addition and Multiplication


解答例

n=int(input())

k=int(input())
s=1
for i in range(n):s=min(s*2,s+k)
print(s)

ABC094 B - Toll Gates


解答例

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

s=sum(int(i)<x for i in input().split())
print(min(s,m-s))

ABC113 B - Palace


解答例

n=int(input())

t,a=map(int,input().split())
h=list(map(int,input().split()))
z=[abs(t-x*0.006-a) for x in h]
print(z.index(min(z))+1)

ABC037 A - 饅頭


解答例

a,b,c=map(int,input().split())

print(c//min(a,b))

ABC040 A - 赤赤赤赤青


解答例

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

print(min(x-1,n-x))

ABC066 A - ringring


解答例

a,b,c=map(int,input().split())

print(min(a+b,b+c,c+a))

ABC080 A - Parking


解答例

n,a,b=map(int,input().split())

print(min(n*a,b))

ABC092 A - Traveling Budget


解答例

a,b,c,d=[int(input()) for _ in range(4)]

print(min(a,b)+min(c,d))

ABC103 A - Task Scheduling Problem


解答例

A=list(map(int,input().split()))

print(max(A)-min(A))

ABC120 A - Favorite Sound


解答例

a,b,c=map(int,input().split())

print(min(c,b//a))


4.4 合計値

ABC015 B - 高橋くんの集計


解答例

n=int(input())

a=list(map(int,input().split()))
print(-(-sum(a)//(n-a.count(0))))

ABC051 B - Sum of Three Integers


解答例

k,s=map(int,input().split())

print(sum(0<=s-y-z<=k for z in range(k+1) for y in range(k+1)))

ABC067 B - Snake Toy


解答例

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

print(sum(sorted(map(int,input().split()))[-k:]))


解答例

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

print(sum(sorted(map(int,input().split()))[::-1][:k]))

ABC115 B - Christmas Eve Eve


解答例

l=[int(input()) for _ in range(int(input()))]

print(sum(l)-int(max(l)/2))


解答例

n=int(input())

p=sorted([int(input()) for i in range(n)])
print(p[-1]//2+sum(p[:-1]))

ABC117 B - Polygon


解答例

input()

L=list(map(int,input().split()))
print("Yes" if sum(L)>2*max(L) else "No")


解答例

input()

L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")

ABC017 A - プロコン


解答例

print(sum(eval(input().replace(' ','*')) for i in range(3))//10)


ABC063 A - Restricted


解答例

x=sum(map(int,input()[::2]))

print(x if x<10 else "error")

ABC066 A - ringring


解答例

print(sum(sorted(map(int,input().split()))[:2]))



数字和


  • 数字和:digit sum


サンプルコード

x=1234

print(sum(map(int,x)))


実行結果

10(=1+2+3+4)


ABC080 B - Harshad Number


解答例

n=input()

print("No" if int(n)%sum(map(int,n)) else "Yes")

ABC083 B - Some Sums


解答例

n,a,b=map(int,input().split())

print(sum(i for i in range(n+1) if a<=sum(map(int,str(i)))<=b))


解答例

n,a,b=map(int,input().split())

ans=0
for i in range(n+1):
if a<=sum(map(int,str(i)))<=b:ans+=i
print(ans)


解答例

n,a,b=map(int,input().split())

s=0
for i in range(n+1):
if a<=sum(int(j) for j in str(i))<=b:
s+=i
print(s)


解答例

n,a,b=map(int,input().split())

s=0
for i in range(n+1):
c=0
d=str(i)
for j in range(len(d)):
c+=int(d[j])
if a<=c<=b:
s+=i
print(s)

ABC101 B - Digit Sums


解答例

N=input()

print("Yes" if int(N)%sum(map(int,list(N)))==0 else "No")


解答例

N=input()

print("Yes" if int(N)%sum(int(_) for _ in N)==0 else "No")


解答例

N=input()

s=0
for n in N:
s+=int(n)
print("Yes" if int(N)%s==0 else "No")

ABC023 A - 加算王


解答例

print(sum(map(int,input())))



4.5 絶対値


サンプルコード

print(abs(-1))



実行結果

1


ABC056 B - NarrowRectanglesEasy


解答例

w,a,b=map(int,input().split())

print(max(abs(a-b)-w,0))

ABC114 B - 754


解答例

s=input()

print(min(abs(int(s[i:i+3])-753) for i in range(len(s))))

ABC071 A - Meal Delivery


解答例

x,a,b=map(int,input().split())

print("A" if abs(a-x)<abs(b-x) else "B")


4.6 置換


サンプルコード

List=["aabbaa","bbaabb","ababab"]

List=",".join(List)
print(List)


実行結果

aabbaa,bbaabb,ababab



サンプルコード

List=List.replace('a','c')

print(List)


実行結果

ccbbcc,bbccbb,cbcbcb



サンプルコード

List=List.split(',')

print(List)


実行結果

['ccbbcc', 'bbccbb', 'cbcbcb']



サンプルコード

List=["aabbaa", "bbaabb", "ababab"]

List=",".join(List).replace('a', 'c').split(',')
print(List)


実行結果

['ccbbcc', 'bbccbb', 'cbcbcb']


ABC017 A - プロコン


解答例

print(sum(eval(input().replace(' ','*')) for i in range(3))//10)


ABC027 A - 長方形


解答例

print(eval(input().replace(' ','^')))


ABC107 A - Train


解答例

print(eval(input().replace(" ","-"))+1)


ABC109 A - ABC333


解答例

print("No" if eval(input().replace(" ","*"))%2==0 else "Yes")


ABC111 A - AtCoder Beginner Contest 999


解答例

print(input().replace("1","x").replace("9","1").replace("x","9"))


ABC117 A - Entrance Examination


解答例

print(eval(input().replace(" ","/")))



第5章 応用処理観点


5.1 行列


行集計

\begin{pmatrix}

1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{pmatrix}
\begin{pmatrix}
1 \\
1 \\
1 \\
\end{pmatrix}
=
\begin{pmatrix}
6 \\
15 \\
24 \\
\end{pmatrix}


サンプルコード

Matrix=[[1,2,3],[4,5,6],[7,8,9]]

print([sum(Row) for Row in Matrix])


実行結果

[6, 15, 24]



列集計

\begin{pmatrix}

1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{pmatrix}^T
\begin{pmatrix}
1 \\
1 \\
1 \\
\end{pmatrix}
=
\begin{pmatrix}
12 \\
15 \\
18 \\
\end{pmatrix}


サンプルコード

Matrix=[[1,2,3],[4,5,6],[7,8,9]]

print([sum(Row) for Row in zip(*Matrix)])


実行結果

[12, 15, 18]



転置行列

A =

\begin{pmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{pmatrix}

A^T =

\begin{pmatrix}
1 & 4 & 7 \\
2 & 5 & 8 \\
3 & 6 & 9 \\
\end{pmatrix}


サンプルコード

Matrix=[[1,2,3],[4,5,6],[7,8,9]]

for Row in zip(*Matrix):print(Row)


実行結果

(1, 4, 7)

(2, 5, 8)
(3, 6, 9)

ABC107 B - Grid Compression


解答例

h,w=map(int,input().split())

a=[[j for j in input()] for i in range(h)]
b=[x for x in a if "#" in x]
c=zip(*[y for y in zip(*b) if "#" in y])
for d in c:print("".join(d))


回転行列

A =

\begin{pmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{pmatrix}

A^{回転} =

\begin{pmatrix}
3 & 6 & 9 \\
2 & 5 & 8 \\
1 & 4 & 7 \\
\end{pmatrix}

ABC004 B - 回転


解答例

print("\n".join(input() for _ in range(4))[::-1])



解答例

for i in reversed([input() for i in range(4)]):

print(i[::-1])

ABC036 B - 回転


解答例

s=[input() for i in range(int(input()))]

for x in zip(*s):print("".join(x)[::-1])


解答例

s=reversed([input() for i in range(int(input()))])

for x in zip(*s):print("".join(x))


順位行列

ABC004 C - ID


解答例

import collections

import bisect
n,m=map(int,input().split())
p=[[int(j) for j in input().split()] for i in range(m)]
a=collections.defaultdict(list)
for x,y in sorted(p):
a[x]+=[y]
for x,y in p:
z=bisect.bisect(a[x],y)
print("%06d%06d"%(x,z))


5.2 グリッド

ABC096 C - Grid Repainting 2


解答例

H,W=map(int,input().split())

S=["."+input()+"." for i in range(H)]
S=["."*(W+2)]+S+["."*(W+2)]
flag=0
for i in range(H):
for j in range(W):
if S[i][j]=="#":
if S[i-1][j]=="." and S[i+1][j]=="." and S[i][j-1]=="." and S[i][j+1]==".":
flag=1
print("Yes" if flag==0 else "No")

ABC049 B - たてなが / Thin


解答例

h,w=map(int,input().split())

for i in range(h):
s=input()
print(s+"\n"+s)

ABC054 B - Template Matching


解答例

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

a=[input() for _ in range(n)]
b=[input() for _ in range(m)]
r=any([r[j:j+m] for r in a[i:i+m]]==b for i in range(n-m+1) for j in range(n-m+1))
print('Yes' if r else 'No')

ABC062 B - Picture Frame


解答例

h,w=map(int,input().split())

print("#"*(w+2))
for i in range(h):print("#"+input()+"#")
print("#"*(w+2))

ABC075 B - Minesweeper


解答例

h,w=map(int,input().split())

s=[input() for _ in range(h)]
for i in range(h):
l=""
for j in range(w):
if s[i][j]=="#":
l+="#"
else:
l+=str(sum([t[max(0,j-1):min(w,j+2)].count("#") for t in s[max(0,i-1):min(h,i+2)]]))
print(l)

ABC107 B - Grid Compression


解答例

h,w=map(int,input().split())

a=[[j for j in input()] for i in range(h)]
b=[x for x in a if "#" in x]
c=zip(*[y for y in zip(*b) if "#" in y])
for d in c:print("".join(d))


5.3 数列

ABC050 C - Lining Up


解答例

import math

N=int(input())
A=list(map(int,input().split()))
flag=True
if N%2==0:
if 0 in A or len(set(A))!=N//2:flag=False
else:
if len([0 for a in A if a==0])!=1 or len(set(A))!=N//2+1:flag=False
if flag:print(2**(N//2)%(10**9+7))
else:print(0)

ABC059 C - Sequence


解答例

n=input()

a=[int(i) for i in input().split()]
def chk(a,t):
ans=0
x=0
for i in a:
x+=i
if t==True and x<1:
ans+=1-x
x=1
elif t==False and x>-1:
ans+=x+1
x=-1
t=not t
return ans
print(min(chk(a,True),chk(a,False)))

ABC087 C - Candies


解答例

n=int(input())

a=list(map(int,input().split()))
b=list(map(int,input().split()))
print(max(sum(a[:i+1])+sum(b[i:]) for i in range(n)))


解答例

n=int(input())

a=list(map(int,input().split()))
b=list(map(int,input().split()))
ans=0
for i in range(n):
ans=max(ans,sum(a[:i+1])+sum(b[i:]))
print(ans)

ABC092 C - Traveling Plan


解答例

N=int(input())

A=[0]+list(map(int,input().split()))+[0]
cost=sum(abs(A[i+1]-A[i]) for i in range(N+1))
for i in range(1,N+1):
print(cost-abs(A[i+1]-A[i])-abs(A[i]-A[i-1])+abs(A[i+1]-A[i-1]))


解答例

N=int(input())

A=list(map(int,input().split()))+[0]
A.insert(0,0)
cost=0
for i in range(N+1):
cost+=abs(A[i+1]-A[i])
for i in range(1,N+1):
print(cost-abs(A[i+1]-A[i])-abs(A[i]-A[i-1])+abs(A[i+1]-A[i-1]))

ABC093 C - Same Integers


解答例

l=sorted(map(int,input().split()))

a=2*l[2]-l[1]-l[0]
print((a+3)//2 if a%2 else a//2)

ABC100 C - *3 or /2


解答例

n=int(input())

a=list(map(int,input().split()))
c=0
for i in a:
while i%2==0:i,c=i/2,c+1
print(c)


5.4 再帰

ABC115 D - Christmas


解答例

N,X=map(int,input().split())

a,p=[1],[1]
for i in range(N):
a.append(a[i]*2+3)
p.append(p[i]*2+1)
def f(n,x):
if n==0:return 0 if x<=0 else 1
elif x<=1+a[n-1]:return f(n-1,x-1)
else:return p[n-1]+1+f(n-1,x-2-a[n-1])
print(f(N,X))


5.5 グラフ

ARC030 A - 閉路グラフ


解答例

N=int(input())

K=int(input())
print("YES" if K<=N//2 else "NO")

ABC016 C - 友達の友達


解答例

V,E=map(int,input().split())

edges=[set() for i in range(V)]
for i in range(E):
a,b=map(int,input().split())
edges[a-1].add(b-1)
edges[b-1].add(a-1)
for i in range(V):
print(len({n for v in edges[i] for n in edges[v] if not n in edges[i] and n!=i}))

ABC054 C - One-stroke Path


解答例

import itertools

N,M=map(int,input().split())
edges={tuple(sorted(map(int,input().split()))) for i in range(M)}
ans=0
for i in itertools.permutations(range(2,N+1),N-1):
l=[1]+list(i)
ans+=sum(1 for edge in zip(l,l[1:]) if tuple(sorted(edge)) in edges)==N-1
print(ans)

ABC075 C - Bridge


解答例

N,M=map(int,input().split())

edges=[list(map(int,input().split())) for i in range(M)]
ans=0
for x in edges:
l=list(range(N))
for y in edges:
if y!=x:l=[l[y[0]-1] if l[i]==l[y[1]-1] else l[i] for i in range(N)]
if len(set(l))!=1:ans+=1
print(ans)

ABC021 B - 嘘つきの高橋くん


解答例

input()

a=input().split()
input()
a+=input().split()
print("YES" if len(a)==len(set(a)) else "NO")

ABC061 B - Counting Roads


解答例

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

l=[]
for i in range(m):l+=list(map(int,input().split()))
for i in range(1,n+1):print(l.count(i))


  • 未分類

ABC012 D - バスと避けられない運命

ABC014 D - 閉路

ABC019 D - 高橋くんと木の直径

ABC035 D - トレジャーハント

ABC051 D - Candidates of No Shortest Paths

ABC061 D - Score Attack

ABC070 D - Transit Tree Path

ABC073 D - joisino's travel

ABC074 D - Restoring Road Network


第6章 アルゴリズム観点


ユークリッドの互除法


  • 2つの自然数の最大公約数を求める手法

ユークリッドの互除法 - Wikipedia


サンプルコード

a,b=12,8

x,y=max(a,b),min(a,b)
while y!=0:x,y=y,x%y
print(x)


実行結果

4


ABC032 A - 高橋君と青木君の好きな数


解答例

a,b,n=[int(input()) for i in range(3)]

while n%a!=0 or n%b!=0:n+=1
print(n)


最大公約数


  • GCD:Greatest Common Divisor


サンプルコード

from functools import reduce

from fractions import gcd
List=[15,25,30]
print(reduce(gcd,List))


実行結果

5


ABC109 C - Skip


解答例

from functools import reduce

from fractions import gcd
N,X=map(int,input().split())
x=[abs(X-int(i)) for i in input().split()]
print(reduce(gcd,x))

ABC118 C - Monsters Battle Royale


解答例

import functools,fractions

n=input()
a=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,a))


最小公倍数


  • LCM:Least Common Multiple


サンプルコード

from functools import reduce

from fractions import gcd
def lcm(x,y):return x*y//gcd(x,y)
def lcmm(l):return reduce(lcm,l)
List=[15,25,30]
print(lcmm(List))


実行結果

150


ABC070 C - Multiple Clocks


解答例

from fractions import gcd

def lcm(a,b): return a*b//gcd(a,b)
N=int(input())
ans=1
for i in range(N):
t=int(input())
ans=lcm(ans,t)
print(ans)

ABC118 C - Monsters Battle Royale


解答例

import functools,fractions

n=input()
a=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,a))

ABC032 A - 高橋君と青木君の好きな数


解答例

a,b,n=[int(input()) for i in range(3)]

while n%a!=0 or n%b!=0:n+=1
print(n)


DP


  • DP:Dynamic Programming(動的計画法)

動的計画法 - Wikipedia

ABC118 D - Match Matching


解答例

N,M=map(int,input().split())

A=list(map(int,input().split()))
d=[0]*N*9+[-1]*N*9
for i in range(1,N+1):d[i]=max(d[i-int("0255456376"[a])]*10+a for a in A)
print(d[N])


解答例

N,M=map(int,input().split())

A=list(map(int,input().split()))
weight=[0,2,5,5,4,5,6,3,7,6]
dp=[-1]*(N+1)
dp[0]=0
for i in range(N+1):
for a in A:
if i+weight[a]<N+1:
dp[i+weight[a]]=max(dp[i+weight[a]],dp[i]*10+a)
print(dp[N])

ABC040 C - 柱柱柱柱柱


解答例

N=int(input())

A=list(map(int,input().split()))+[0]
dp=[0]*N
dp[1]=abs(A[1]-A[0])
for i in range(1,N-1):
dp[i+1]=min(dp[i]+abs(A[i+1]-A[i]),dp[i-1]+abs(A[i+1]-A[i-1]))
print(dp[N-1])

ABC011 C - 123引き算


解答例

N=int(input())

NG=[int(input()) for i in range(3)]
dp=[float("INF")]*301
dp[N]=0
for i in range(N,0,-1):
if i in NG:continue
for j in range(1,4):
dp[i-j]=min(dp[i]+1,dp[i-j])
print("YES" if dp[0]<=100 else "NO")


  • 未解答

ABC122 D - We Like AGC

ABC034 C - 経路


DFS


  • DFS:Depth First Search(深さ優先探索)

深さ優先探索 - Wikipedia

ABC114 C - 755


解答例

N = int(input())

def dfs(s):
if int(s)>N:
return 0;
ret = 1 if all(s.count(c) > 0 for c in "753") else 0
for c in "753":
ret += dfs(s+c)
return ret
print(dfs("0"))


  • 未解答

ABC054 C - One-stroke Path


BFS


  • BFS:Breadth First Search(幅優先探索)

幅優先探索 - Wikipedia

ABC007 C - 幅優先探索


解答例

h,w=map(int,input().split())

sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
grid=[list(input()) for x in range(h)]
grid[sy-1][sx-1]=0
loc=[[sy-1,sx-1]]
for k in range(1,h*w):
next_loc=[]
for y,x in loc:
for i,j in ([1,0],[-1,0],[0,1],[0,-1]):
if grid[y+i][x+j]=='.':
grid[y+i][x+j]=k
next_loc.append([y+i,x+j])
loc=next_loc
if [gy-1,gx-1] in loc:
break
print(k)


UnionFind

素集合データ構造 - Wikipedia


  • 未解答

ABC040 D - 道路の老朽化対策について

ABC120 D - Decayed Bridges

ABC075 C - Bridge

ABC054 C - One-stroke Path

ABC015 C - 高橋くんのバグ探し


しゃくとり法

ABC032 C - 列


解答例

N,K=map(int,input().split())

S=[int(input()) for i in range(N)]
length=left=0
mul=1
if 0 in S:
length=N
else:
for right in range(N):
mul*=S[right]
if mul<=K:
length=max(length,right-left+1)
else:
mul//=S[left]
left+=1
print(length)


解答例(TLE)

N,K=map(int,input().split())

S=[int(input()) for i in range(N)]
length=0
if 0 in S:
length=N
else:
for i in range(N):
for j in range(i+1,N):
mul=1
for k in range(i,j+1):
mul*=S[k]
if mul<=K:
length=max(length,j-i+1)
print(length)

ABC038 C - 単調増加


解答例

N=int(input())

A=list(map(int,input().split()))
diff=0
ans=N
for i in range(N-1):
if A[i]<A[i+1]:
diff+=1
ans+=diff
else:
diff=0
print(ans)


全探索

ABC045 C - たくさんの数式 / Many Formulas


解答例

S=input()

ans=0
for i in range(len(S)):
for j in range(i+1):
ans+=int(S[-(i+1)])*(10**j)*(2**(len(S)-1))//(2**min(i,j+1))
print(ans)


解答例

S=input()

ans=0
for i in range(2**(len(S)-1)):
tmp=S[0]
for j in range(len(S)-1):
if i&(1<<j):tmp+="+"
tmp+=S[j+1]
ans+=eval(tmp)
print(ans)

ABC080 C - Shopping Street


解答例

N=int(input())

F=[int(input().replace(' ',''),2) for i in range(N)]
P=[list(map(int,input().split())) for i in range(N)]
print(max(sum([p[bin(f&i).count('1')] for f,p in zip(F,P)]) for i in range(1,2**10)))

ABC107 C - Candles


解答例

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

x=sorted(list(map(int,input().split())))
print(min((min(abs(x[i])+abs(x[i+k-1]-x[i]),abs(x[i+k-1])+abs(x[i]-x[i+k-1]))) for i in range(n-k+1)))


解答例

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

x=sorted(list(map(int,input().split())))
a=[]
for i in range(n-k+1):
l=x[i]
r=x[i+k-1]
a.append(min(abs(l)+abs(r-l),abs(r)+abs(l-r)))
print(min(a))

ARC029 A - 高橋君とお肉


解答例

N=int(input())

T=sorted(int(input()) for i in range(N))[::-1]
x=y=0
for t in T:
if x<y:x+=t
else:y+=t
print(max(x,y))

ARC041 A - コインの反転


解答例

x,y=map(int,input().split())

k=int(input())
print(x+y-abs(k-y))


  • 未分類

ABC002 D - 派閥

ABC018 D - バレンタインデー

ABC031 D - 語呂合わせ

ABC039 D - 画像処理高橋君

ABC075 D - Axis-Parallel Rectangle


貪欲法

ABC011 C - 123引き算


解答例

N=int(input())

NG=[int(input()) for i in range(3)]
if N in NG:
print("NO")
exit()
for i in range(100):
N-=3
if N in NG:
N+=1
if N in NG:
N+=1
if N in NG:
print("NO")
exit()
print("YES" if N<=0 else "NO")

ABC048 C - Boxes and Candies


解答例

A=list(map(int,input().split()))+[0]

ans=0
for i in range(N):
eated=max(0,A[i]+A[i-1]-x)
ans+=eated
A[i]-=eated
print(ans)


最大フロー

最大フロー問題 - Wikipedia


  • 未分類

ABC010 D - 浮気予防


エラトステネスのふるい

エラトステネスの篩 - Wikipedia


  • 未解答

ABC084 D - 2017-like Number


ワーシャル–フロイド法

ワーシャル–フロイド法 - Wikipedia


  • 未解答

ABC016 C - 友達の友達


クラスカル法/プリム法

クラスカル法 - Wikipedia

プリム法 - Wikipedia


  • 未解答

ARC076 D - Built?


第7章 計算量観点


剰余

ABC055 B - Training Camp


解答例

import math

print(math.factorial(int(input()))%(10**9+7))


解答例

ans=1

n=int(input())
for i in range(1,n+1):
ans*=i
ans=ans%(10**9+7)
print(ans)


解答例(TLE)

ans=1

n=int(input())
for i in range(1,n+1):
ans*=i
print(ans%(10**9+7))


ソート

ABC004 C - 入れ替え


解答例

N=int(input())%30

X=[1,2,3,4,5,6]
for i in range(N):
tmp=X[i%5+1]
X[i%5+1]=X[i%5]
X[i%5]=tmp
print(*X,sep="")


解答例(TLE)

N=int(input())

X=[1,2,3,4,5,6]
for i in range(N):
tmp=X[i%5+1]
X[i%5+1]=X[i%5]
X[i%5]=tmp
print(*X,sep="")


つるかめ算

ABC006 C - スフィンクスのなぞなぞ


解答例

N,M=map(int,input().split())

if 2*N<=M<=4*N:
y=M%2
z=((M-3*y)-2*(N-y))//2
x=N-y-z
print(x,y,z)
else:
print("-1 -1 -1")


解答例(TLE)

N,M=map(int,input().split())

for x in range(N+1):
for y in range(N+1):
z=N-x-y
if 2*x+3*y+4*z==M and z>=0:
print(x,y,z)
exit()
print("-1 -1 -1")


いもす法

ABC017 C - ハイスコア


解答例

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

imos=[0]*(m+1)
t=0
for i in range(n):
l,r,s=map(int,input().split())
imos[l-1]+=s
imos[r]-=s
t+=s
for i in range(m):
imos[i+1]+=imos[i]
print(t-min(imos[:-1]))

ABC035 C - オセロ


解答例

N,Q=map(int,input().split())

O=[0]*(N+1)
for i in range(Q):
l,r=map(int,input().split())
O[l-1]+=1
O[r]-=1
for i in range(N):
if i>0:O[i]+=O[i-1]
print(O[i]%2,end="")
print()


解答例(TLE)

N,Q=map(int,input().split())

O=[0]*N
for i in range(Q):
l,r=map(int,input().split())
for j in range(l,r+1):
O[j-1]+=1
for i in range(N):
if O[i]%2==0:
O[i]=0
else:
O[i]=1
print(*O,sep="")

ABC014 C - AtColor


解答例

N=int(input())

n=10**6+1
x=[0]*(n+1)
for i in range(N):
a,b=map(int,input().split())
x[a]+=1
x[b+1]-=1
for i in range(n):
x[i+1]+=x[i]
print(max(x))


  • 未分類

ABC001 D - 感雨時刻の整理


累積和


  • 累積和:Cumulative sum


サンプルコード

List=[0,1,2,3,4,5,6,7,8,9,10]

for i in range(1,len(List)):List[i]+=List[i-1]
print(List)


実行結果

[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]


ABC067 C - Splitting Pile


解答例

N=int(input())

A=list(map(int,input().split()))
S=sum(A)
T=[0]*N
for i in range(N-1):
T[i+1]=T[i]+A[i]
print(min(abs(S-2*T[i]) for i in range(1,N)))


解答例(TLE)

N=int(input())

A=list(map(int,input().split()))
print(min(abs(sum(A[:i])-sum(A[i:])) for i in range(1,N)))

ABC098 C - Attention


解答例

N=int(input())

S=input()
cnt=S.count("E")
m=cnt
for i in S:
if i=="E":
cnt-=1
else:
cnt+=1
m=min(m,cnt)
print(m)

ABC122 C - GeT AC


解答例

N,Q=map(int,input().split())

S=input()
count=[0]*N
for i in range(1,N):
count[i]+=count[i-1]
if S[i-1:i+1]=="AC":count[i]+=1
for i in range(Q):
l,r=map(int,input().split())
print(count[r-1]-count[l-1])


  • 未分類

ABC009 D - 漸化式


二分探索

ABC119 D - Lazy Faith


解答例

import bisect

A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
x=int(input())
i=bisect.bisect_right(S,x)
j=bisect.bisect_right(T,x)
d=INF
for s in [S[i-1],S[i]]:
for t in [T[j-1],T[j]]:
d1=abs(s-x)+abs(s-t)
d2=abs(t-x)+abs(s-t)
d=min(d,d1,d2)
print(d)

ABC030 C - 飛行機乗り


解答例

import bisect

N,M=map(int,input().split())
X,Y=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
ans=0
time=0
while time<=A[-1]:
time=A[bisect.bisect_left(A,time)]+X
if time<=B[-1]:
time=B[bisect.bisect_left(B,time)]+Y
ans+=1
else:break
print(ans)

ABC084 C - Snuke Festival


解答例

import bisect

N=int(input())
A=sorted(list(map(int,input().split())))
B=sorted(list(map(int,input().split())))
C=sorted(list(map(int,input().split())))
print(sum(bisect.bisect_left(A,b)*(N-bisect.bisect_right(C,b)) for b in B))


解答例(TLE)

from collections import Counter

N=int(input())
A=Counter(input().split())
B=Counter(input().split())
C=Counter(input().split())
ans=0
for a_key,a_count in A.most_common():
for b_key,b_count in B.most_common():
for c_key,c_count in C.most_common():
a_key,b_key,c_key=int(a_key),int(b_key),int(c_key)
if a_key<b_key and b_key<c_key:
ans+=a_count*b_count*c_count
print(ans)


  • 未分類

ABC023 D - 射撃王

ABC026 D - 高橋君ボール1号

ABC034 D - 食塩水


中央値の算出


解答例

N=int(input())

X=list(map(int,input().split()))
S=sorted(X)
b=S[N//2]
a=S[(N//2)-1]
for i in X:
print(b if i<b else a)


解答例

N=int(input())

X=list(map(int,input().split()))
s=[]
for i in range(N):
s=sorted(X[:i]+X[i+1:])
print(s[N//2-1])


条件式によるループ回数削減

ABC097 B - Exponential


解答例

x=int(input())

c=1
for b in range(1,x):
for p in range(2,x):
if b**p<=x:c=max(c,b**p)
else:break # b**pがx以上は計算を省く
print(c)


解答例(TLE)

x=int(input())

c=1
for b in range(1,x):
for p in range(2,x):
if b**p<=x:c=max(c,b**p)
print(c)


処理中の剰余算(10*n+7)

ABC034 C - 経路


解答例

from math import factorial

W,H=map(int,input().split())
m=10**9+7
print(factorial(W+H-2)*pow(factorial(H-1)*factorial(W-1)%m,m-2,m)%m)

ABC065 C - Reconciled?


解答例

import math

N,M=map(int,input().split())
print(max(2-abs(N-M),0)*math.factorial(N)*math.factorial(M)%(10**9+7))

ABC006 B - トリボナッチ数列


解答例

a,b,c=0,0,1

for i in range(int(input())-1):
a,b,c=b,c,(a+b+c)%10007
print(a)


解答例(TLE)

a,b,c=0,0,1

for i in range(int(input())-1):
a,b,c=b,c,a+b+c
print(a%10007)

ABC041 B - 直方体


解答例

print(eval(input().replace(" ","*"))%(10**9+7))



方程式

ABC085 C - Otoshidama


解答例

N,Y=map(int,input().split())

for x in range(N+1):
for y in range(N-x+1):
z=N-x-y
if 0<=z<=2000 and 10000*x+5000*y+1000*z==Y:
print(x,y,z)
exit()
print(-1,-1,-1)

ABC051 B - Sum of Three Integers


解答例

k,s=map(int,input().split())

print(sum(0<=s-y-z<=k for z in range(k+1) for y in range(k+1)))


解答例

k,s=map(int,input().split())

print(len([1 for z in range(k+1) for y in range(k+1) if 0<=s-y-z<=k]))


解答例(TLE)

k,s=map(int,input().split())

print([x+y+z for z in range(k+1) for y in range(k+1) for x in range(k+1)].count(s))


部分数列の総和

ABC037 C - 総和


解答例

N,K=map(int,input().split())

A=list(map(int,input().split()))
print(sum(A[i]*min(i+1,K,N-i,N-K+1) for i in range(N)))


解答例(TLE)

N,K=map(int,input().split())

A=list(map(int,input().split()))
print(sum(sum(A[i:i+K]) for i in range(N-K+1)))


キュー

ABC077 C - pushpush


解答例

N=int(input())

A=list(map(int,input().split()))
print(*A[::-2],*A[N%2::2])


解答例(TLE)

N=int(input())

A=list(map(int,input().split()))
B=[]
for i in range(N):
B.append(A[i])
B=B[::-1]
print(*B)


桁数

ABC057 C - Digits in Multiplication


解答例

N=int(input())

i=int(N**(1/2))
while N%i!=0:
i-=1
print(len(str(N//i)))


解答例

def ketasu(N):

count=1
while N>=10:
N//=10
count+=1
return count
N=int(input())
keta=10**10
for i in range(1,int(N**.5)+1):
if N%i==0:
keta=min(keta,max(ketasu(i),ketasu(N//i)))
print(keta)


第8章 数学観点


和差算

ABC096 B - Maximum Sum


解答例

a,b,c=sorted(map(int, input().split()))

print(a+b+c*2**int(input()))


解答例

l=[int(_) for _ in input().split()]

k=int(input())
print(sum(l)-max(l)+max(l)*2**k)

ABC110 A - Maximize the Formula


解答例

print(eval('+'.join(sorted(input()))+'*10'))



解答例

A,B,C=sorted(map(int,input().split()))

print(10*C+B+A)

ABC111 A - AtCoder Beginner Contest 999


解答例

print(1110-int(input()))



数直線

ABC119 D - Lazy Faith


解答例

import bisect

A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
x=int(input())
i=bisect.bisect_right(S,x)
j=bisect.bisect_right(T,x)
d=INF
for s in [S[i-1],S[i]]:
for t in [T[j-1],T[j]]:
d1=abs(s-x)+abs(s-t)
d2=abs(t-x)+abs(s-t)
d=min(d,d1,d2)
print(d)

ABC060 C - Sentou


解答例

N,T=map(int,input().split())

t=list(map(int,input().split()))
ans=0
for i in range(N-1):
ans+=min(t[i+1]-t[i],T)
print(ans+T)

ABC107 C - Candles


解答例

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

x=sorted(list(map(int,input().split())))
print(min((min(abs(x[i])+abs(x[i+k-1]-x[i]),abs(x[i+k-1])+abs(x[i]-x[i+k-1]))) for i in range(n-k+1)))


解答例

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

x=sorted(list(map(int,input().split())))
a=[]
for i in range(n-k+1):
l=x[i]
r=x[i+k-1]
a.append(min(abs(l)+abs(r-l),abs(r)+abs(l-r)))
print(min(a))

ABC117 C - Streamline


解答例

N,M=map(int,input().split())

X=sorted(set(list(map(int,input().split()))))
s=[]
for i in range(M-1):
s.append(X[i+1]-X[i])
s=sorted(s)[::-1]
print(sum(s[N-1:]))

ABC024 B - 自動ドア


解答例

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

a=b=0
for i in range(n):
s=int(input())
if s>b:a+=s-b
b=s+t
print(b-a)

ABC025 B - 双子とスイカ割り


解答例

n,a,b=map(int,input().split())

x=0
for i in range(n):
s,d=input().split()
d=int(d)
if s=="East":
if d<a:d=a
if d>b:d=b
else:
if d<a:d=a
if d>b:d=b
d=-d
x+=d
print("0" if x==0 else "East "+str(x) if x>0 else "West "+str(abs(x)))

ABC064 B - Traveling AtCoDeer Problem


解答例

input()

l=sorted(map(int,input().split()))
print(l[-1]-l[0])


解答例

input()

a=list(map(int,input().split()))
print(max(a)-min(a))

ABC070 B - Two Switches


解答例

a,b,c,d=map(int,input().split())

print(max(0,min(b,d)-max(a,c)))


解答例

a,b,c,d=map(int,input().split())

t=len(set(map(int,range(a,b+1)))&set(map(int,range(c,d+1))))-1
print("0" if t==-1 else t)

ABC093 B - Small and Large Integers


解答例

a,b,k=map(int,input().split())

r=range(a,b+1)
for i in sorted(set(r[:k])|set(r[-k:])):print(i)

ABC110 B - 1 Dimensional World's Tale


解答例

N,M,X,Y=map(int,input().split())

x=list(map(int,input().split()))+[X]
y=list(map(int,input().split()))+[Y]
print("No War" if max(x)<min(y) else "War")


円と長方形


解答例

x,y,r=map(int,input().split())

a,b,c,d=map(int,input().split())
if a<=x-r and x+r<=c and b<=y-r and y+r<=d:print("NO")
else:print("YES")
if max((a-x)**2,(c-x)**2)+max((b-y)**2,(d-y)**2)<=r**2:print("NO")
else:print("YES")


座標

ABC051 C - Back and Forth


解答例

sx,sy,tx,ty=map(int,input().split())

ans=[]

for i in range(ty-sy):
ans.append("U")
for i in range(tx-sx):
ans.append("R")
for i in range(abs(sy-ty)):
ans.append("D")
for i in range(abs(sx-tx)):
ans.append("L")

ans.append("L")
for i in range(ty-sy+1):
ans.append("U")
for i in range(tx-sx+1):
ans.append("R")
ans.append("D")
ans.append("R")
for i in range(abs(sy-ty)+1):
ans.append("D")
for i in range(abs(sx-tx)+1):
ans.append("L")
ans.append("U")

print("".join(ans))


ABC035 B - ドローン


解答例

s=input()

d=abs(s.count("L")-s.count("R"))+abs(s.count("U")-s.count("D"))
q=s.count("?")
if int(input())==1:print(d+q)
else:print(max(len(s)%2,d-q))

ABC074 B - Collecting Balls (Easy Version)


解答例

input()

k=int(input())
print(sum(min(x,k-x)*2 for x in map(int,input().split())))

ABC108 B - Ruined Square


解答例

x1,y1,x2,y2=map(int,input().split())

x=x2-x1
y=y2-y1
print(x2-y,y2+x,x1-y,y1+x)


面積

ABC062 C - Chocolate Bar


解答例

h,w=map(int,input().split())

pattern=[h//2+w//3+1,h//3+w//2+1,h,w]
if h%3==0 or w%3==0:
pattern+=[0]
if h%2==0:
pattern+=[h//2]
if w%2==0:
pattern+=[w//2]
print(min(pattern))

ABC047 B - すぬけ君の塗り絵 2 イージー / Snuke's Coloring 2 (ABC Edit)


解答例

w,h,n=map(int,input().split())

b=c=0
for _ in range(n):
x,y,a=map(int,input().split())
if a==1:b=max(b,x)
if a==2:w=min(w,x)
if a==3:c=max(c,y)
if a==4:h=min(h,y)
print(max(0,(w-b))*max(0,(h-c)))


解答例

w,h,n=map(int,input().split())

l=[[int(j) for j in input().split()] for i in range(n)]
b=c=0
for i in range(n):
x,y,a=l[i][0],l[i][1],l[i][2]
if a==1:b=max(b,x)
if a==2:w=min(w,x)
if a==3:c=max(c,y)
if a==4:h=min(h,y)
print([(w-b)*(h-c),0][(w<b)|(h<c)])

ABC016 A - Right Triangle


解答例

a,b,c=map(int,input().split())

print(a*b//2)

ABC039 A - 高橋直体


解答例

a,b,c=map(int,input().split())

print(2*(a*b+b*c+c*a))

ABC045 A - 台形 / Trapezoids


解答例

a,b,h=[int(input()) for i in range(3)]

print((a+b)*h//2)

ABC052 A - Two Rectangles


解答例

a,b,c,d=map(int,input().split())

print(max(a*b,c*d))


倍数

AGC028 A - Two Abbreviations


解答例

from fractions import gcd

N,M=map(int,input().split())
S=list(input())
T=list(input())
L=gcd(N,M)
print(N*M//L if all([S[i*N//L]==T[i*M//L] for i in range(L)]) else "-1")

ABC100 B - Ringo's Favorite Numbers


解答例

D,N=map(int,input().split())

l=[int(pow(100,D)*i) for i in range(1,N+1)]
print(l[N-1])


約数


  • 約数:Divisor


サンプルコード

N=100

divisor=[i for i in range(1,N+1) if N%i==0]
print(divisor)


実行結果

[1, 2, 4, 5, 10, 20, 25, 50, 100]


ABC106 B - 105


解答例

N=int(input())

count=0
for i in range(105,N+1,2):
divisor=0
for j in range(1,i+1):
if(i%j==0):divisor+=1
if(divisor==8):count+=1
print(count)

ABC120 B - K-th Common Divisor


解答例

A,B,K=map(int,input().split())

print([n for n in range(1,min(A,B)+1) if A%n==B%n==0][-K])


解答例

A,B,K=map(int,input().split())

a=[n for n in range(1,A+1) if A%n==0]
b=[n for n in range(1,B+1) if B%n==0]
print(sorted(set(a)&set(b))[::-1][K-1])

ABC118 A - B +/- A


解答例

a,b=map(int,input().split())

print(b-a if b%a>0 else a+b)


素数


  • 素数:Prime number


サンプルコード

N=101

print("Prime" if all([N%i for i in range(2,int(N**.5)+1)]) else "Not prime")


実行結果

Prime



サンプルコード

N=102

print("Prime" if all([N%i for i in range(2,int(N**.5)+1)]) else "Not prime")


実行結果

Not prime


ARC017 A - 素数、コンテスト、素数


解答例

N=int(input())

print("YES" if all([N%n for n in range(2,int(N**.5)+1)]) else "NO")


解答例

N=int(input())

print("YES" if all([N%n for n in range(2,N)]) else "NO")


解答例

N=int(input())

print("NO" if any([N%n==0 for n in range(2,N)]) else "YES")

ARC032 A - ホリドッグ


解答例

N=int(input())

S=sum(n for n in range(N+1))
flag=0
for s in range(2,S):
if S%s==0:
flag=1
print("WANWAN" if flag==0 and N!=1 else "BOWWOW")

ARC044 A - 素数判定


解答例

N=int(input())

flag=1
if N==1:flag=0
elif N==2 or N==3 or N==5:flag=1
elif N%2==0 or N%3==0 or N%5==0:flag=0
else:flag=1
print("Prime" if flag==1 else "Not Prime")


素因数分解


  • 素因数分解:Factoring


サンプルコード

for num in range(2,10):

i=num
Factoring=[]
flag=True
while flag:
for j in range(2,num+1):
if i%j==0:
i=i/j
if i==1:flag=False
Factoring.append(j)
break
if len(Factoring)==1:print(num,"is a prime")
else:print(num,Factoring)


実行結果

2 is a prime

3 is a prime
4 [2, 2]
5 is a prime
6 [2, 3]
7 is a prime
8 [2, 2, 2]
9 [3, 3]


約数の個数

ある整数 $ x $ が素因数分解によって $ x= p^n × q^m × ... (p,q,...は素数) $ と表される時、 $ x $ の約数の個数は $ (n+1) × (m+1) × ... $ となる。

ABC114 D - 756


解答例

N=int(input())

e=[0]*(N+1)
for i in range(2,N+1):
cur=i
for j in range(2,i+1):
while cur%j==0:
e[j]+=1
cur//=j
def num(m):return len(list(filter(lambda x:x>=m-1,e)))
print(num(75)+num(25)*(num(3)-1)+num(15)*(num(5)-1)+num(5)*(num(5)-1)*(num(3)-2)//2)

ABC067 C - Factors of Factorial


解答例

import math

N=math.factorial(int(input()))
i=2
ans=1
M=10**9+7
while i*i<=N:
cnt=1
while N%i==0:
cnt+=1
N//=i
ans*=cnt
i+=1
if N!=1:ans*=2
print(int(ans%M))


順列


  • 順列:permutation

_4 P _2 = 4 \times 3 = 12通り


サンプルコード

from itertools import permutations

List=["a","b","c","d"]
print(list(permutations(List,2)))


実行結果

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]



サンプルコード

from itertools import permutations

List=["a","b","c","d"]
print(len(list(permutations(List,2))))


実行結果

12



サンプルコード

from itertools import permutations

List=["a","b","c","d"]
print(list(permutations(List,2)))


実行結果

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]



サンプルコード

from itertools import permutations

List=["a","b","c","d"]
print(len(list(permutations(List,2))))


実行結果

12


ARC013 A - 梱包できるかな?


解答例

from itertools import permutations

n,m,l=map(int,input().split())
P=list(map(int,input().split()))
v=0
for p,q,r in permutations(P):
v=max(v,(n//p)*(m//q)*(l//r))
print(v)


組み合わせ


  • 組み合わせ:combination

_4 C _2 = \frac{_4 P _2}{2!} = 6通り


サンプル

from itertools import combinations

List=["a","b","c","d"]

print(list(combinations(List,2)))
# [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

print(len(list(combinations(List,2))))
# 6


ABC028 C - 数を3つ選ぶマン


解答例

from itertools import combinations

S=map(int,input().split())
print(sorted(map(sum,combinations(S,3)))[-3])

ABC089 C - March


解答例

from itertools import combinations

from collections import Counter
N=int(input())
S=Counter()
for i in range(N):
S[input()[0]]+=1
print(sum([S[a]*S[b]*S[c] for a,b,c in combinations("MARCH",3)]))

ABC108 A - Pair


解答例

K=int(input())

print((K//2)*((K+1)//2))


経路

\frac{(width+height -2)!}{(width-1)!(height -1)!}

ABC034 C - 経路


解答例

from math import factorial

W,H=map(int,input().split())
m=10**9+7
print(factorial(W+H-2)*pow(factorial(H-1)*factorial(W-1)%m,m-2,m)%m)


色塗り

ABC046 B - AtCoDeerくんとボール色塗り / Painting Balls with AtCoDeer


解答例

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

print(k*(k-1)**(n-1))


重複組み合わせ


サンプルコード

from itertools import combinations_with_replacement

List=["a","b","c","d"]
print(list(combinations_with_replacement(List,3)))


実行結果

[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'a', 'd'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'c'), ('a', 'c', 'd'), ('a', 'd', 'd'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'b', 'd'), ('b', 'c', 'c'), ('b', 'c', 'd'), ('b', 'd', 'd'), ('c', 'c', 'c'), ('c', 'c', 'd'), ('c', 'd', 'd'), ('d', 'd', 'd')]



サンプルコード

from itertools import combinations_with_replacement

List=["a","b","c","d"]
print(len(list(combinations_with_replacement(List,3))))


実行結果

20


ABC011 D - 大ジャンプ

ABC021 D - 多重ループ


直積


サンプルコード

from itertools import product

A=["a","b","c"]
X=["x","y","z"]
for p in product(A,X):
print(p)


実行結果

('a', 'x')

('a', 'y')
('a', 'z')
('b', 'x')
('b', 'y')
('b', 'z')
('c', 'x')
('c', 'y')
('c', 'z')


サンプルコード

from itertools import product

A=["a","b","c"]
X=["x","y","z"]
for a,x in product(A,X):
print(a,x)


実行結果

a x

a y
a z
b x
b y
b z
c x
c y
c z


サンプルコード

from itertools import product

for p in product("357",repeat=3):
print("".join(p))


実行結果

333

335
337
353
355
357
373
375
377
533
535
537
553
555
557
573
575
577
733
735
737
753
755
757
773
775
777


確率


  • 未分類

ABC024 D - 動的計画法

ABC028 D - 乱数生成


期待値

ABC078 C - HSI


解答例

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

print((1900*m+100*(n-m))*2**m)

ABC003 A - AtCoder社の給料


解答例

print((int(input())+1)*5e3)



数列の和

f(x) = \sum_{1}^n x = \frac{n(n + 1)}{2}


サンプルコード

n=10

print(n*(n+1)//2)


実行結果

55



サンプルコード

n=10

print(n*-~n//2)


実行結果

55



サンプルコード

n=10

print(sum(range(n+1)))


実行結果

55


ABC099 B - Stone Monument


解答例

a,b=map(int,input().split())

n=b-a
print(n*(n+1)//2-b)

ABC043 A - キャンディーとN人の子供イージー / Children and Candies (ABC Edit)


解答例

n=int(input())

print(n*-~n//2)


解答例

n=int(input())

print(n*(n+1)//2)


連立方程式の解

2x+3y+4z=10 (0≦x<20, 0≦y<30, 0≦z<40)


サンプルコード

List=[(x,y,z) for z in range(40) for y in range(30) for x in range(20) if 2*x+3*y+4*z==10]

print(List)
List=list(map(list,set(List)))
print(List)
print(len(List))


実行結果

[(5, 0, 0), (2, 2, 0), (3, 0, 1), (0, 2, 1), (1, 0, 2)]

[[2, 2, 0], [3, 0, 1], [0, 2, 1], [5, 0, 0], [1, 0, 2]]
5


  • 解に条件がある場合

2x+3y+4z=10 (0≦x<20, 0≦y<30, 0≦z<40, x+y+z=4)


サンプルコード

List=[(x,y,z) for z in range(40) for y in range(30) for x in range(20) if 2*x+3*y+4*z==10 and x+y+z==4]

print(List)
List=list(map(list,set(List)))
print(List)
print(len(List))


実行結果

[(2, 2, 0), (3, 0, 1)]

[[3, 0, 1], [2, 2, 0]]
2


連立方程式の解の個数

2x+3y+4z=10 (0≦x<20, 0≦y<30, 0≦z<40)


サンプルコード

print([2*x + 3*y + 4*z for z in range(40) for y in range(30) for x in range(20)].count(10))



実行結果

5



サンプルコード

print(len([1 for x in range(20) for y in range(30) for z in range(40) if 2*x+3*y+4*z==10]))



実行結果

5


x+y+z=S (0≦x, y, z<k≦2500)(0≦S<3K)


サンプルコード

s=7000

k=2500
print(len([1 for y in range(k) for x in range(k) if 0<=s-x-y<=k]))


実行結果

124750



サンプルコード

s=7000

k=2500
print([1 for y in range(k) for x in range(k) if 0<=s-x-y<=k].count(1))


実行結果

124750


ABC087 B - Coins


解答例

a,b,c,x=[int(input()) for _ in range(4)]

print([500*x+100*y+50*z for z in range(c+1) for y in range(b+1) for x in range(a+1)].count(x))

ABC105 B - Cakes and Donuts


解答例

print("Yes" if [4*x+7*y for y in range(101) for x in range(101)].count(int(input())) else "No")



平方根の整数部と小数部の算出

y = x^{1/2} (a:整数部, b:小数部)


サンプルコード

a,b=divmod(5,2)

print(a)
print(b)


実行結果

2

1


サンプルコード

# 平方値

print(2**.5)
# 整数値
print(int(2**.5))
# 小数値
y=2**.5
x=y-int(y)
print(x)


実行結果

1.4142135623730951

1
0.41421356237309515

ABC077 B - Around Square


解答例

print(int(int(input())**.5)**2)



相加相乗平均

\frac{a+b}{2} ≧ \sqrt{ab}

ABC026 A - 掛け算の最大値


解答例

print(int(input())**2//4)



解答例

n=int(input())

print((n//2)*(-(-n//2)))


ユークリッド距離

distance(\boldsymbol{x},\boldsymbol{y}) = \sqrt{\sum_{i=1}^n(x_i - y_i)^2}

\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}

ARC004 A - 2点間距離の最大値 ( The longest distance )


解答例

p=[list(map(int,input().split())) for i in range(int(input()))]

print(max(((a[0]-b[0])**2+(a[1]-b[1])**2)**.5 for b in p for a in p))


解答例

import math

p=[list(map(int,input().split())) for i in range(int(input()))]
print(max(math.hypot(a[0]-b[0],a[1]-b[1]) for b in p for a in p))


解答例

N=int(input())

p=[]
for i in range(N):
x,y=map(int,input().split())
p.append([x,y])
d=0
for i in range(N):
for j in range(N):
if i!=j:d=max(d,((p[i][0]-p[j][0])**2+(p[i][1]-p[j][1])**2)**.5)
print(d)


マンハッタン距離

distance(\boldsymbol{x},\boldsymbol{y}) = \sum_{i=1}^n|x_i - y_i|

|x_1 - x_2| + |y_1 - y_2|

ABC057 B - Checkpoints


解答例

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

ab=[[int(j) for j in input().split()] for i in range(n)]
cd=[[int(j) for j in input().split()] for i in range(m)]
for a,b in ab:
l=[abs(a-c)+abs(b-d) for c,d in cd]
print(l.index(min(l))+1)


解答例

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

a=[[int(j) for j in input().split()] for i in range(n)]
c=[[int(j) for j in input().split()] for i in range(m)]
for i in range(n):
d=10e8
b=0
for j in range(m):
if abs(a[i][0]-c[j][0])+abs(a[i][1]-c[j][1])<d:
d=abs(a[i][0]-c[j][0])+abs(a[i][1]-c[j][1])
b=j+1
print(b)


ヘロンの公式

S = \sqrt{s(s-a)(s-b)(s-c)} \\

s = \frac{a+b+c}{2}

ヘロンの公式 - Wikipedia

ABC002 C - 直訴


解答例

x1,y1,x2,y2,x3,y3=map(int,input().split())

a=((x1-x2)**2+(y1-y2)**2)**.5
b=((x2-x3)**2+(y2-y3)**2)**.5
c=((x3-x1)**2+(y3-y1)**2)**.5
s=(a+b+c)/2
print((s*(s-a)*(s-b)*(s-c))**.5)


コラッツ予想

f(n) = \left\{

\begin{array}{ll}
n / 2 & (if\;\;n=0) \\
3n + 1 & (if\;\;n=1)
\end{array}
\right.

コラッツの問題 - Wikipedia

ABC116 B - Collatz Problem


解答例

S=int(input())

l=[]
while (S not in l):
l.append(S)
if S%2==0:S//=2
else:S=3*S+1
print(len(l)+1)


必要十分条件

P \rightarrow Q


解答例

x,y,r=map(int,input().split())

a,b,c,d=map(int,input().split())
if a<=x-r and x+r<=c and b<=y-r and y+r<=d:print("NO")
else:print("YES")
if max((a-x)**2,(c-x)**2)+max((b-y)**2,(d-y)**2)<=r**2:print("NO")
else:print("YES")


第9章 カテゴリ観点


日時

ARC023 A - 経過日数


解答例

import datetime

y=int(input())
m=int(input())
d=int(input())
print((datetime.date(2014,5,17)-datetime.date(y,m,d)).days)


解答例

Y=int(input())

M=int(input())
D=int(input())
if M==1 or M==2:
Y-=1
M+=12
print(735369-(365*Y+Y//4-Y//100+Y//400+306*(M+1)//10+D-429))

ABC012 B - 入浴時間


解答例

n=int(input())

print("%02d:%02d:%02d"%(n//3600,(n%3600)//60,n%60))

ABC096 A - Day of Takahashi


解答例

a,b=map(int,input().split())

print(a-1 if a>b else a)

ABC119 A - Still TBD


解答例

print("Heisei" if input()<="2019/04/30" else "TBD")



時計

ABC030 B - 時計盤


解答例

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

a=abs(n%12*30-5.5*m)
print(min(a,360-a))


コイン

ARC041 A - コインの反転


解答例

x,y=map(int,input().split())

k=int(input())
print(x+y-abs(k-y))


オセロ

AGC090 A - Irreversible operation


解答例

s=input()

ans=0
count=0 if s[0]=="B" else 1
for i in range(1,len(s)):
if s[i]=="W":
ans+=i-count
count+=1
print(ans)


カード

ABC090 C - Flip,Flip, and Flip......


解答例

N,M=map(int,input().split())

print(1 if N==1 and M==1 else max(N,M)-2 if N==1 or M==1 else N*M-2*N-2*M+4)


宝くじ

ARC006 A - 宝くじ


解答例

E=set(input().split())

b=input()
L=set(input().split())
l=len(E&L)
ans=0
if l==5 and b in L:ans=2
elif l==6:ans=1
elif l>2:ans=8-l
else:ans=0
print(ans)


解答例

a = [int(i) for i in input().split()]

b = int(input())
c = [int(i) for i in input().split()]
k = 6 - len(set(a) - set(c))
if k == 5 and b in c: print(2)
else: print({6:1,5:3,4:4,3:5}.get(k,0))


ゾロ目

ARC046 A - ゾロ目数


解答例

N=int(input())-1

print(str(N%9+1)*(N//9+1))


解答例

N=int(input())

num=1
while N>0:
if len(set(str(num)))==1:N-=1
num+=1
print(num-1)


N値判定


  • 2値判定(Zero/NotZero判定)

f(x) = \left\{

\begin{array}{ll}
Zero & (x=0) \\
Not Zero & (x\neq0)
\end{array}
\right.


サンプルコード

x=int(input())

print(["Not Zero","Zero"][x==0])

x
0
1

x==0
True
False

["Not Zero","Zero"][x==0]
Zero
Not Zero

ABC056 A - HonestOrDishonest


解答例

print("HD"[len(set(input()))%2])


ABC099 A - ABD


解答例

print(['ABC','ABD'][len(input())>3])


ABC102 A - Multiple of 2 and N


解答例

n=int(input())

print([N,N*2][N%2])


  • 2値判定(奇数/偶数判定、入力数1)

f(x) = \left\{

\begin{array}{ll}
Even & (x\;\;mod\;\;2\;\;=\;\;0) \\
Odd & (x\;\;mod\;\;2\;\;=\;\;1)
\end{array}
\right.


サンプルコード

x=int(input())

print(["Even","Odd"][x%2])

x
1
2

x%2
1
0

["Even","Odd"][x%2]
Odd
Even

ARC014 A - 君が望むなら世界中全てのたこ焼きを赤と青に染め上げよう


解答例

print("Blue" if int(input())%2==0 else "Red")



  • 2値判定(奇数/偶数判定、入力数2)

f(x,y) = \left\{

\begin{array}{ll}
Even & (x y\;\;mod\;\;2\;\;=\;\;0) \\
Odd & (x y\;\;mod\;\;2\;\;=\;\;1)
\end{array}
\right.


サンプルコード

x,y=map(int,input().split())

print(["Even","Odd"][x*y%2])

x*y
1
2

x*y%2
1
0

["Even","Odd"][x*y%2]
Odd
Even


  • 2値判定(奇数/偶数判定、入力複数)

f(\boldsymbol{x}) = \left\{

\begin{array}{ll}
Even & (if\;\;x_{i}\;\;mod\;\;2\;\;=\;\;0) \\
Odd & (otherwise)
\end{array}
\right.


サンプルコード

x=[2,4,6,8]

print("Even" if all([i%2==0 for i in x]) else "Odd")


実行結果

Even



サンプルコード

x=[2,4,6,9]

print("Even" if all([i%2==0 for i in x]) else "Odd")


実行結果

Odd



  • 3値判定(正の数/0/負の数判定)

f(x) = \left\{

\begin{array}{ll}
Positive & (x > 0) \\
0 & (x = 0) \\
Negative& (x < 0)
\end{array}
\right.


サンプルコード

x=int(input())

print(["0","Positive","Negative"][x>0 or -(x<0)])

x
-1
0
1

x>0
False
False
True

x<0
True
False
Flase

-(x<0)
-1
0
0

x>0 or -(x<0)
-1
0
True

["0","Positive","Negative"][x>0 or -(x<0)]
Negative
0
Positive

ABC078 A - HEX


解答例

x,y=input().split()

print("=><"[x>y or -(x<y)])

ABC083 A - Libra


解答例

a,b,c,d=map(int,input().split())

print(['Balanced','Left','Right'][(a+b>c+d)-(a+b<c+d)])

ABC104 A - Rated for Me


解答例

print(["ABC","ARC","AGC"][(int(input())+400)//1600])



第10章 実装観点


10.1 import


bisect


サンプルコード

import bisect

List=[ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(bisect.bisect_left(List,5))
# 2
"""
List=[ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
1 2 3 4 5 6 7 8 9 10
^
"""

print(bisect.bisect_right(List,5))
# 3
"""
List=[ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
1 2 3 4 5 6 7 8 9 10
^
"""

print(bisect.bisect_left(List,15))
# 7
"""
List=[ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
1 2 3 4 5 6 7 8 9 10
^
"""

print(bisect.bisect_right(List,15))
# 8
"""
List=[ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
1 2 3 4 5 6 7 8 9 10
^
"""

List=[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
print(bisect.bisect_left(List,2))
# 4
"""
List=[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
1 2 3 4 5 6 7 8 9 10 11 12
^
"""

print(bisect.bisect_right(List,2))
# 8
"""
List=[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
1 2 3 4 5 6 7 8 9 10 11 12
^
"""

print(bisect.bisect_right(List,2))
# 8
"""
List=[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
1 2 3 4 5 6 7 8 9 10 11 12
^
"""

print(bisect.bisect_right(List,3))
# 12
"""
List=[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
1 2 3 4 5 6 7 8 9 10 11 12
^
"""


ABC119 D - Lazy Faith


解答例

import bisect

A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
x=int(input())
i=bisect.bisect_right(S,x)
j=bisect.bisect_right(T,x)
d=INF
for s in [S[i-1],S[i]]:
for t in [T[j-1],T[j]]:
d1=abs(s-x)+abs(s-t)
d2=abs(t-x)+abs(s-t)
d=min(d,d1,d2)
print(d)

ABC084 C - Snuke Festival


解答例

import bisect

N=int(input())
A=sorted(list(map(int,input().split())))
B=sorted(list(map(int,input().split())))
C=sorted(list(map(int,input().split())))
print(sum(bisect.bisect_left(A,b)*(N-bisect.bisect_right(C,b)) for b in B))


解答例

from collections import Counter

N=int(input())
A=Counter(input().split())
B=Counter(input().split())
C=Counter(input().split())
ans=0
for a_key,a_count in A.most_common():
for b_key,b_count in B.most_common():
for c_key,c_count in C.most_common():
a_key,b_key,c_key=int(a_key),int(b_key),int(c_key)
if a_key<b_key and b_key<c_key:
ans+=a_count*b_count*c_count
print(ans)


calendar


  • isleap

うるう年:Leap year

ARC002 A - うるう年


解答例

import calendar

print("YES" if calendar.isleap(int(input())) else "NO")


collections


  • Counter


サンプルコード

List=['a','a','a','a','b','c','c']

c=collections.Counter(l)
print(c)
# Counter({'a': 4, 'c': 2, 'b': 1})
print(type(c))
# <class 'collections.Counter'>
print(issubclass(type(c), dict))
# True
print(c.keys())
# dict_keys(['a', 'b', 'c'])
print(c.values())
# dict_values([4, 1, 2])
print(c.items())
# dict_items([('a', 4), ('b', 1), ('c', 2)])
print(c.most_common())
# [('a', 4), ('c', 2), ('b', 1)]
print(c.most_common()[0])
# ('a', 4)
print(c.most_common()[-1])
# ('b', 1)
print(c.most_common()[0][0])
# a
print(c.most_common()[0][1])
# 4
print(c.most_common()[::-1])
# [('b', 1), ('c', 2), ('a', 4)]
print(c.most_common(2))
# [('a', 4), ('c', 2)]
values,counts=zip(*c.most_common())
print(values)
# ('a', 'c', 'b')
print(counts)
# (4, 2, 1)
print(c['a'])
# 4
print(c['b'])
# 1
print(c['c'])
# 2
print(c['d'])
# 0

ARC024 A - くつがくっつく


解答例

from collections import Counter

input()
L=Counter(input().split())
R=Counter(input().split())
print(sum([min(value,L[key]) for key,value in R.items()]))

ARC081 C - Make a Rectangle


解答例

from collections import Counter

N=int(input())
A=Counter(list(map(int,input().split())))
x=[0,0]
for a in A:
if A[a]>1:x.append(a)
if A[a]>3:x.append(a)
x.sort()
print(x[-1]*x[-2])

ABC071 C - 怪文書 / Dubious Document


解答例

from collections import Counter

n=int(input())
s=Counter(input())
for i in range(n-1):
s&=Counter(input())
print("".join(sorted(s.elements())))

ABC073 C - Write and Erase


解答例

from collections import Counter

N=int(input())
A=Counter([int(input()) for i in range(N)])
print(sum(1 if count%2 else 0 for count in A.values()))

ABC081 C - Not so Diverse


解答例

from collections import Counter

n,k=map(int,input().split())
a=Counter(input().split())
print(sum(sorted(a.values(),reverse=True)[k:]))


解答例

from collections import Counter

n,k=map(int,input().split())
a=Counter(input().split())
ans=0
keys,counts=zip(*a.most_common())
for num,(key,count) in enumerate(zip(keys,counts)):
if int(num)>k-1:ans+=count
print(ans)

ABC082 C - Good Sequence


解答例

from collections import Counter

n=int(input())
a=Counter(input().split())
ans=0
for i,j in a.items():
i=int(i)
if i>j:
ans+=j
elif i<j:
ans+=j-i
print(ans)

ABC103 C - /\/\/\/


解答例

from collections import Counter

n=int(input())
v=list(map(int,input().split()))
a=Counter(v[0::2]).most_common()
b=Counter(v[1::2]).most_common()
a.append([0,0])
b.append([0,0])
if a[0][0]!=b[0][0]:
print(n-(a[0][1]+b[0][1]))
else:
print(min(n-(a[1][1]+b[0][1]),n-(a[0][1]+b[1][1])))

ABC110 C - String Transformation


解答例

from collections import Counter

s=Counter(list(input()))
t=Counter(list(input()))
s,t=list(s.values()),list(t.values())
print("Yes" if sorted(s)==sorted(t) else "No")

ABC008 B - 投票


解答例

from collections import Counter

print(Counter([input() for i in range(int(input()))]).most_common()[0][0])


  • deque


サンプルコード

from collections import deque

queue=deque(["a","b","c"])
queue.append("d")
print(queue)
queue.popleft()
print(queue)


実行結果

deque(['a', 'b', 'c', 'd'])

deque(['b', 'c', 'd'])


fractions


  • fraction:分数


  • gcd


ABC118 C - Monsters Battle Royale


解答例

import functools,fractions

n=input()
a=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,a))


functools


  • functools:高次関数


  • reduce



サンプル

from functools import reduce

from operator import add
from operator import sub
from operator import mul
List=[20,1,2,3,4,5]
print(reduce(add,List))
# 35(=20+1+2+3+4+5)
print(reduce(sub,List))
# 5(=20-1-2-3-4-5)
print(reduce(mul,List))
# 2300(=20*1*2*3*4*5)

# Lambda式に変換が可能
print(reduce(lambda a,b:a+b,List)) # 35
print(reduce(lambda a,b:a-b,List)) # 5
print(reduce(lambda a,b:a*b,List)) # 2400

ABC109 C - Skip


解答例

from functools import reduce

from fractions import gcd
N,X=map(int,input().split())
x=[abs(X-int(i)) for i in input().split()]
print(reduce(gcd,x))


heapq


サンプルコード

import heapq

hq=[2,-20,5,0,-1,100,27]
heapq.heappush(hq,-30)
print(hq)
heapq.heappop(hq)
print(hq)
print(heapq.nlargest(3,hq))
print(heapq.nsmallest(3,hq))


実行結果

[-30, 2, 5, -20, -1, 100, 27, 0]

[2, -20, 5, 0, -1, 100, 27]
[100, 27, 5]
[-20, -1, 0]

ARC081 C - Make a Rectangle


解答例

import heapq

N=int(input())
s=set()
q=[0,0]
for a in map(int,input().split()):
if a>q[0]:
try:
s.remove(a)
heapq.heapreplace(q,a)
except:
s.add(a)
print(q[0]*q[1])


itertools


  • permutations

4! = 4 × 3 × 2 × 1 = 24通り


サンプルコード

from itertools import permutations

List=["a","b","c","d","e"]
print(list(permutations(List)))
print(len(list(permutations(List))))


実行結果

[('a', 'b', 'c', 'd'), ('a', 'b', 'd', 'c'), ('a', 'c', 'b', 'd'), ('a', 'c', 'd', 'b'), ('a', 'd', 'b', 'c'), ('a', 'd', 'c', 'b'), ('b', 'a', 'c', 'd'), ('b', 'a', 'd', 'c'), ('b', 'c', 'a', 'd'), ('b', 'c', 'd', 'a'), ('b', 'd', 'a', 'c'), ('b', 'd', 'c', 'a'), ('c', 'a', 'b', 'd'), ('c', 'a', 'd', 'b'), ('c', 'b', 'a', 'd'), ('c', 'b', 'd', 'a'), ('c', 'd', 'a', 'b'), ('c', 'd', 'b', 'a'), ('d', 'a', 'b', 'c'), ('d', 'a', 'c', 'b'), ('d', 'b', 'a', 'c'), ('d', 'b', 'c', 'a'), ('d', 'c', 'a', 'b'), ('d', 'c', 'b', 'a')]

24

_4 P _2 = 4 \times 3 = 12通り


サンプルコード

from itertools import permutations

List=["a","b","c"]
print(list(permutations(List,2)))
print(len(list(permutations(List,2))))


実行結果

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]

12

ARC013 A - 梱包できるかな?


解答例

from itertools import permutations

n,m,l=map(int,input().split())
P=list(map(int,input().split()))
v=0
for p,q,r in permutations(P):
v=max(v,(n//p)*(m//q)*(l//r))
print(v)


  • product

ABC029 C - Brute-force Attack


解答例

from itertools import product

[print("".join(i)) for i in product("abc",repeat=int(input()))]

ABC114 C - 755


解答例

import itertools

N=int(input())
ans=0
S=[]
for i in range(10):
S+=list(itertools.product("357",repeat=i))
for s in S:
if len(set(s))>2 and int("".join(s))<=N:
ans+=1
print(ans)


  • groupby

ABC063 C - 一次元リバーシ / 1D Reversi


解答例

from itertools import groupby

S=input()
G=groupby(S)
print(len(list(G))-1)

ABC019 B - 高橋くんと文字列圧縮


解答例

import itertools

print("".join([i+str(len(list(j))) for i,j in itertools.groupby(list(input()))]))


解答例

import itertools

s=""
for i,j in itertools.groupby(list(input())):
s+=i+str(len(list(j)))
print(s)


  • combinations

_4 C _2 = \frac{_4 P _2}{2!} = 6通り


サンプル

from itertools import combinations

List=["a","b","c","d"]
print(list(combinations(List,2)))
# [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
print(len(list(combinations(List,2))))
# 6

ABC028 C - 数を3つ選ぶマン


解答例

from itertools import combinations

S=map(int,input().split())
print(sorted(map(sum,combinations(S,3)))[-3])

ABC089 C - March


サンプルコード

from itertools import combinations

for a,b,c in combinations("MARCH",3):
print(a,b,c)


実行結果

M A R

M A C
M A H
M R C
M R H
M C H
A R C
A R H
A C H
R C H


解答例

from itertools import combinations

from collections import Counter
N=int(input())
S=Counter()
for i in range(N):
S[input()[0]]+=1
print(sum([S[a]*S[b]*S[c] for a,b,c in combinations("MARCH",3)]))


math


  • ceil


サンプルコード

import math

print(math.ceil(5/3))


実行結果

2



  • factorial

ABC067 C - Factors of Factorial


解答例

import math

N=math.factorial(int(input()))
i=2
ans=1
M=10**9+7
while i*i<=N:
cnt=1
while N%i==0:
cnt+=1
N//=i
ans*=cnt
i+=1
if N!=1:ans*=2
print(int(ans%M))

ABC055 B - Training Camp


解答例

import math

print(math.factorial(int(input()))%(10**9+7))


  • floor


サンプルコード

import math

print(math.floor(5/3))


実行結果

1



  • pow


サンプルコード

import math

print(math.pow(2,3))


実行結果

8.0



  • sqrt


サンプルコード

import math

print(math.sqrt(4))


実行結果

2.0



10.2 組み込み関数


abs


サンプルコード

print(abs(-1))



実行結果

1



all/any


  • all


サンプルコード

print(all([True,True]))



実行結果

True



サンプルコード

print(all([True,False]))



実行結果

False



サンプルコード

print(all([False,False]))



実行結果

False


ABC044 B - 美しい文字列 / Beautiful Strings


解答例

s=input()

print("Yes" if all([s.count(i)%2==0 for i in set(s)]) else "No")

ABC081 B - Shift only


解答例

input()

A=list(map(int,input().split()))
ans=0
while all(a%2==0 for a in A):
A=[a/2 for a in A]
ans+=1
print(ans)


解答例

n=int(input())

A=list(map(int,input().split()))
ans=0
while all(a%2==0 for a in A):
for i in range(n):
A[i]=A[i]/2
ans+=1
print(ans)

ABC109 B - Shiritori


解答例

n=int(input())

w=[input() for i in range(n)]
flag=False
if n==len(set(w)):
if all([w[i-1][-1]==w[i][0] for i in range(1,n)]):
flag=True
print("Yes" if flag else "No")


  • any


サンプルコード

print(any([True,True]))



実行結果

True



サンプルコード

print(any([True,False]))



実行結果

True



サンプルコード

print(any([False,False]))



実行結果

False


ABC060 B - Choose Integers


解答例

a,b,c=map(int,input().split())

print("YES" if any((a*i)%b==c for i in range(1,b+1)) else "NO")


divmod


サンプルコード

a,b=divmod(5,2)

print(a)
print(b)


実行結果

2

1


enumerate


サンプルコード

List=['Alice', 'Bob', 'Charlie']

for num,name in enumerate(List):
print(num,name)


実行結果

0 Alice

1 Bob
2 Charlie

ABC041 C - 背の順


解答例

N=int(input())

A=[(int(a), i) for i,a in enumerate(input().split(),1)]
for a in sorted(A,reverse=True):
print(a[1])

ABC102 C - Linear Approximation


解答例

N=int(input())

A=sorted(a-i-1 for i,a in enumerate(map(int,input().split())))
print(sum(abs(a-A[N//2]) for a in A))


eval


サンプルコード

print(eval("1+2"))



実行結果

3


ARC018 A - BMI


解答例

print(eval(input().replace(" ","**2*"))/1e4)


ABC041 B - 直方体


解答例

print(eval(input().replace(" ","*"))%(10**9+7))


ABC073 B - Theater


解答例

print(sum(1-eval(input().replace(" ","-")) for _ in range(int(input()))))


ABC016 A - 12月6日


解答例

print("NO" if eval(input().replace(" ","%")) else "YES")


ABC017 A - プロコン


解答例

print(sum(eval(input().replace(' ','*')) for i in range(3))//10)


ABC035 A - テレビ


解答例

print("4:3" if eval(input().replace(" ","*"))%144 else "16:9")


ABC050 A - Addition and Subtraction Easy


解答例

print(eval(input()))



map

ABC110 C - String Transformation


解答例

s=input()

t=input()
S=sorted(map(s.count,set(s)))
T=sorted(map(t.count,set(t)))
print("Yes" if S==T else "No")


max/min


  • max


サンプルコード

print(max(1,2))



実行結果

2



サンプルコード

print(max(2,1,3))



実行結果

3



サンプルコード

print(max([2,1,3]))



実行結果

3



サンプルコード

print(max(['b','a','c','d']))



実行結果

d



サンプルコード

print(max(['ab','aa','ca','bd']))



実行結果

ca



サンプルコード

print(max(['a','bcde','fg','hij'],key=len))



実行結果

bcde



  • min


サンプルコード

print(min(1,2))



実行結果

1



サンプルコード

print(min(2,1,3))



実行結果

1



サンプルコード

print(min([2,1,3]))



実行結果

1



サンプルコード

print(min(['b','a','c','d']))



実行結果

a



サンプルコード

print(min(['ab','aa','ca','bd']))



実行結果

aa



サンプルコード

print(min(['a','bcde','fg','hij'],key=len))

#


実行結果

a



ord/chr


  • ord


サンプルコード

print([chr(i) for i in range(ord('a'),ord('z')+1)])



実行結果

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


ABC013 A - A


解答例

print(ord(input())-64)



  • chr


サンプルコード

print([chr(i) for i in range(97, 97+26)])



実行結果

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']



range


サンプルコード

r=range(2,10)

print(r)


実行結果

range(2, 10)



サンプルコード

r=range(2,10)

print(r[:3])


実行結果

range(2, 5)



サンプルコード

r=range(2,10)

print(set(r[:3]))


実行結果

{2, 3, 4}



サンプルコード

r=range(2,10)

print(r[3:])


実行結果

range(5, 10)



サンプルコード

r=range(2,10)

print(set(r[3:]))


実行結果

{5, 6, 7, 8, 9}



サンプルコード

r=range(2,10)

print(r[-3:])


実行結果

range(7, 10)



サンプルコード

r=range(2,10)

print(set(r[-3:]))


実行結果

{8, 9, 7}



サンプルコード

r=range(2,10)

print(r[:-3])


実行結果

range(2, 7)



サンプルコード

r=range(2,10)

print(set(r[:-3]))


実行結果

{2, 3, 4, 5, 6}



zip


サンプルコード

Matrix=[

[1,2,3],
[4,5,6],
[7,8,9]
]
print(list(map(list,zip(*Matrix))))


実行結果

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]


ARC025 A - ゴールドラッシュ


解答例

print(sum(map(max,zip(*[list(map(int,input().split())) for i in range(2)]))))



解答例

D=map(int,input().split())

J=map(int,input().split())
print(sum(max(d,j) for d,j in zip(D,J)))

ABC058 B - ∵∴∵


解答例

o=list(input())

e=list(input())+[""]
for x,y in zip(o,e):print(x+y,end="")

ABC121 B - Can you solve this?


解答例

N,M,C=map(int,input().split())

B=list(map(int,input().split()))
count=0
for i in range(N):
A=list(map(int,input().split()))
if sum(a*b for a,b in zip(A,B))+C>0:count+=1
print(count)


10.3 メソッド


find/rfind

ABC039 C - ピアニスト高橋君


解答例

S=input()[0:12]

key="WBWBWWBWBWBW"*2
ans=["Do","","Re","","Mi","Fa","","So","","La","","Si"]
print(ans[(key.find(S))])

ABC053 B - A to Z String


解答例

s=input()

print(s.rfind("Z")-s.find("A")+1)


isdecimal/isdigit/isnumeric/isalpha/isalnum


  • isdecimal:全ての文字が十進数字なら真、そうでなければ偽(半角・全角のアラビア数字が真)


サンプルコード

s="1234567890"

print(s.isdecimal())


実行結果

True


ABC084 B - Postal Code


解答例

a,b=map(int,input().split())

s=input()
if 1<=a<=5 and 1<=b<=5:
if s[a]=="-":
if s[0:a].isdecimal() and s[a+1:a+b+1].isdecimal():
print("Yes")
exit()
print("No")


  • isdigit:全ての文字が数字なら真、そうでなければ偽(半角・全角のアラビア数字、特殊数字が真)


サンプルコード

s="\u00B2" # 2乗

print(s.isdigit())


実行結果

True


ARC052 A - 何期生?


解答例

print("".join(i for i in input() if i.isdigit()))



  • isnumeric:全ての文字が数を表す文字なら真、そうでなければ偽(半角・全角のアラビア数字、特殊数字、漢数字が真)


サンプルコード

s="一二三四五六七八九〇壱億参阡萬"

print(s.isnumeric())


実行結果

True



  • isalpha:全ての文字が英字なら真、そうでなければ偽(便宜上「英字」と書いているが、平仮名やカタカナ、漢字なども真)


サンプルコード

s="abcあいうアイウ漢字"

print(s.isalpha())


実行結果

True



  • isalnum::全ての文字が英数字なら真、そうでなければ偽(各文字が上のメソッドで真となれば真)


サンプルコード

s="abc100"

print(s.isalnum())


実行結果

True



replace


サンプルコード

List=["aabbaa","bbaabb","ababab"]

List=",".join(List)
print(List)


実行結果

aabbaa,bbaabb,ababab



サンプルコード

List=List.replace('a','c')

print(List)


実行結果

ccbbcc,bbccbb,cbcbcb



サンプルコード

List=List.split(',')

print(List)


実行結果

['ccbbcc', 'bbccbb', 'cbcbcb']



サンプルコード

List=["aabbaa", "bbaabb", "ababab"]

List=",".join(List).replace('a', 'c').split(',')
print(List)


実行結果

['ccbbcc', 'bbccbb', 'cbcbcb']



サンプルコード

List=["aabbaa", "bbaabb", "ababab"]

List=",".join(List).replace('a', 'c').split(',')
print(List)


実行結果

['ccbbcc', 'bbccbb', 'cbcbcb']


ARC019 A - お買い物クライシス


解答例

S=input()

for b,a in zip("ODIZSB","001258"):
S=S.replace(b,a)
print(S)


解答例

S=input()

b="ODIZSB"
a="001258"
for i in range(6):
S=S.replace(b[i],a[i])
print(S)


解答例

print(input().replace("O","0").replace("D","0").replace("I","1").replace("Z","2").replace("S","5").replace("B","8"))


ARC045 A - スペース高橋君


解答例

print(input().replace("Left","<").replace("Right",">").replace("AtCoder","A"))


ABC017 B - choku語


解答例

print("YES" if input().replace("ch","").replace("o","").replace("k","").replace("u","")=="" else "NO")


ABC020 B - 足し算


解答例

print(2*int(input().replace(" ","")))


ABC041 B - 直方体


解答例

print(eval(input().replace(" ","*"))%(10**9+7))


ABC104 B - AcCepted


解答例

s=input()

print("AC" if "C" in s[2:-1] and "A" in s and s[1:].replace("C","",1).islower() else "WA")

ABC017 A - プロコン


解答例

print(sum(eval(input().replace(' ','*')) for i in range(3))//10)


ABC027 A - 長方形


解答例

print(eval(input().replace(' ','^')))


ABC085 A - Already 2018


解答例

print("2018"+input()[4:])


ABC107 A - Train


解答例

print(eval(input().replace(" ","-"))+1)


ABC109 A - ABC333


解答例

print("No" if eval(input().replace(" ","*"))%2==0 else "Yes")


ABC111 A - AtCoder Beginner Contest 999


解答例

print(input().replace("1","x").replace("9","1").replace("x","9"))



reverse


  • 1次元


サンプルコード

List=[2,1,3]

List.reverse()
print(List)


実行結果

[3, 1, 2]



  • 2次元


サンプルコード

List=[[0,1],[1,1],[1,0],[0,0]]

List.reverse()
print(List)


実行結果

[[0, 0], [1, 0], [1, 1], [0, 1]]



sort


  • 昇順


サンプルコード

List=[2,1,3]

List.sort()
print(List)


実行結果

[1, 2, 3]



サンプルコード

List=[[0,1],[1,1],[1,0],[0,0]]

List.reverse()
print(List)


実行結果

[[0, 0], [1, 0], [1, 1], [0, 1]]



  • 降順


サンプルコード

List=[2,1,3]

List.sort(reverse=True)
print(List)


実行結果

[3, 2, 1]



サンプルコード

List=[[0,1],[1,1],[1,0],[0,0]]

List.sort(key=lambda List:(List[0],List[1]),reverse=True)
print(List)


実行結果

[[1, 1], [1, 0], [0, 1], [0, 0]]



translate/maketrans

ARC019 A - お買い物クライシス


解答例

print(input().translate(str.maketrans("ODIZSB","001258")))



10.4 正規表現


  • 正規表現:Regular Expression


マッチ


  • findall:マッチする部分すべてをリストで返す

ABC122 B - ATCoder


解答例

import re

print(max(map(len,re.findall("[ACGT]*",input()))))

ARC052 A - 何期生?


解答例

import re

print(*re.findall("[0-9]+",input()))


  • match:文字列の先頭がパターンにマッチするかを調べる

ABC049 C - 白昼夢 / Daydream


解答例

import re

print("YES" if re.match("^(dream|dreamer|erase|eraser)+$",input()) else "NO")

ABC076 C - Dubious Document 2


解答例

import re

s=input().replace("?",".")
t=input()
for i in range(len(s)-len(t),-1,-1):
if re.match(s[i:i+len(t)],t):
s=s.replace(".","a")
print(s[:i]+t+s[i+len(t):])
exit()
print("UNRESTORABLE")


解答例

import re

s=input().replace("?",".")
t=input()
for i in range(len(s)-len(t)+1):
if re.match(s[i:i+len(t)],t):
s=s.replace(".","a")
print(s[:i]+t+s[i+len(t):])
exit()
print("UNRESTORABLE")

ABC104 B - AcCepted


解答例

import re

print("AC" if re.match("^A[a-z]+C[a-z]+$",input()) else "WA")


  • split:stringを出現したpatternで分割する

ABC122 B - ATCoder


解答例

import re

print(max(map(len,re.split("[^ACGT]",input()))))


検索


  • search:先頭に限らずパターンにマッチするかを調べる

ARC022 A - スーパーICT高校生


解答例

import re

print("YES" if re.search("i.*c.*t",input().lower()) else "NO")


解答例

import re

print("YES" if re.search("[i|I].*[c|C].*[t|T]",input()) else "NO")


部分置換


  • sub:マッチした部分を置換する

ARC052 A - 何期生?


解答例

import re

print(re.sub("\D","",input()))

ABC002 B - 罠


解答例

import re

print(re.sub("[aiueo]","",input()))

ABC017 B - choku語


解答例

import re

print("NO" if re.sub(r"ch|o|k|u","",input()) else "YES")

ABC023 B - 手芸王


解答例

import re

print(re.sub("[aiueo]","",input()))


10.5 Lambda式

ABC045 A - 台形 / Trapezoids


解答例

x=lambda:int(input())

print((x()+x())*x()//2)

ABC054 A - One Card Poker


解答例

a,b=map(lambda x:(int(x)+13)%15,input().split())

print("Alice" if a>b else "Bob" if a<b else "Draw")

ABC087 A - Buying Sweets


解答例

i=lambda:int(input())

print((i()-i())%i())

ABC092 A - Traveling Budget


解答例

f=lambda:min(int(input()),int(input()))

print(f()+f())


用語


AtCoder用語集


ハーシャッド数


  • 各位の数字和が元の数の約数にある自然数

ハーシャッド数 - Wikipedia

ABC080 B - Harshad Number


解答例

n=input()

print("No" if int(n)%sum(map(int,n)) else "Yes")


リュカ数


  • 初項(最初のリュカ数)を 2、次の項を 1 と定義し、それ以降の項は前の2つの項の和になっている数列

L_0 = 2, L_1 = 1

L_{n+2} = L_n + L_{n+1}

リュカ数 - Wikipedia

ABC079 B - Lucas Number


解答例

a,b=2,1

for i in range(int(input())):
a,b=b,a+b
print(a)


解答例

n=int(input())

l=[2,1]
for i in range(2,n+3):
l.append(l[i-2]+l[i-1])
print(l[n])


トリボナッチ数列

L_0 = 0, L_1 = 0, L_2 = 1

L_{n} = L_{n-1} + L_{n-2} + L_{n-3}

ABC006 B - トリボナッチ数列


解答例

a,b,c=0,0,1

for i in range(int(input())):
a,b,c=b,c,a+b+c
print(a)


参考


参照ページ


関連ページ


AtCoder情報


コーディング規約

PEP 8 -- Style Guide for Python Code

[Pythonコーディング規約]PEP8を読み解く


マークダウン記法