はじめに
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])
!
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
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
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
print("ABC" if input()=="1" else "chokudai")
a,b,c=input()
print("Yes" if a==c else "No")
n=input()
print("Yes" if n[0]==n[2] else "No")
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
a,b=map(int,input().split())
print(b,a)
- 文字列を複数の変数に格納する
Hello world!
a,b=input().split()
print(a)
print(b)
Hello
world!
a,b=input().split()
print(b,a)
a,b,c=input().split(",")
print(a,b,c)
a,_,b=input()
print("DH"[a==b])
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)
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', '!']
- アンパックを使ってリストに格納する
a,*b,c=input()
print(a+str(len(b))+c)
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))
x,a,b=[int(input()) for _ in range(3)]
print((x-a)%b)
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]
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)))))
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]
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']
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
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")
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
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
x=abs(int(input())-int(input()))
print(min(x,10-x))
print(sum(1-eval(input().replace(" ","-")) for _ in range(int(input()))))
print(int(input())-int(input()))
print(int(input())-1)
s,t=map(int,input().split())
print(t-s+1)
a,b,c=map(int,input().split())
print("YES" if b-a==c-b else "NO")
x,t=map(int,input().split())
print("0" if x-t<0 else x-t)
print(int(input())**2-int(input()))
print(-int(input())+2*int(input()))
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)
a,b=map(int,input().split())
print(a*b-(a+b-1))
n,i=map(int,input().split())
print(n-i+1)
乗法
- 乗算:multiplication
print(3*2)
6
print(int(input())*2)
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)
print((["Bad"]*6+["Good"]*3+["Great"]+["Perfect"])[int(input())//10])
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))
a,b,c,d=map(int,input().split())
print(max(a*b,c*d))
n,m=map(int,input().split())
print((n-1)*(m-1))
print(-int(input())+2*int(input()))
a,b=map(int,input().split())
print(a*b-(a+b-1))
ABC115 A - Christmas Eve Eve Eve
print("Christmas"+" Eve"*(25-int(input())))
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
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)
print(10**int(input())+7)
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)
print(int(input())**2-int(input()))
平方根 / べき根
- 平方根:square root
print(4**.5)
2.0
print(4**(1/2))
2.0
print(int(int(input())**.25))
print(int(int(input())**.5)**2)
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
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
x,y,z=map(int,input().split())
print((x-z)//(y+z))
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)
x,y=map(int,input().split())
print(y//x)
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")
n=int(input())
print(n*800-n//15*200)
print(int(input())//3)
print(int(input())**2//4)
k=int(input())
print((k//2)*((k+1)//2))
x,y=map(int,input().split())
print(x+y//2)
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
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)
print(-(-int(input())//2))
print((int(input())+1)//2)
print(5//3+(5%3>0))
a,b=map(int,input().split())
print(-(-b//a))
print(-~sum(map(int,input().split()))//2)
a,b=map(int,input().split())
print(-~(a+b)//2)
a,b,c=map(int,input().split())
print(min(c,b//a))
四捨五入
- 四捨五入:rounding
print(round(5/3))
2
剰余
- 剰余:modulo
print(7%3)
1
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)
n=int(input())
print(n+1 if n%2 else n-1)
print(eval(input().replace(" ","*"))%(10**9+7))
a,b,c=map(int,input().split())
print("YES" if any((a*i)%b==c for i in range(1,b+1)) else "NO")
N=int(input())
print(N//10*100+min(100,N%10*15)
n=int(input())
print(n//2+n%2)
print(int(input())%12+1)
print(-int(input())%int(input()))
a=int(input())
b=int(input())
print((((a//b)+1)*b-a) if a%b!=0 else "0")
m,d=map(int,input().split())
print("NO" if m%d else "YES")
w,h=map(int,input().split())
print("16:9" if w*h%144==0 else "4:3")
a,b=map(int,input().split())
print("Draw" if a==b else "Bob" if (a+13)%15<(b+13)%15 else "Alice")
print(sum(map(int,input().split()))%24)
print("NO" if int(input()[::2])%4 else "YES")
a,b=map(int,input().split())
print("Impossible" if a*b*(a+b)%3 else "Possible")
print(int(input())%9)
a,b=map(int,input().split())
print("Odd" if a*b%2 else "Even")
x,a,b=[int(input()) for _ in range(3)]
print((x-a)%b)
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)
print((eval(input().replace(" ","%"))>0)+0)
N,K=map(int,input().split())
print(0 if N%K==0 else 1)
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
print(~eval(input().replace(" ","-"))+2)
a,b=map(int,input().split())
print(~-a*~-b)
a,b=map(int,input().split())
print(~-a*~-b)
シフト
print(["ABC","ARC","AGC"][int(input())//50+8>>5])
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
a,b,c=0,0,1
for i in range(int(input())-1):
a,b,c=b,c,(a+b+c)%10007
print(a)
a,b=2,1
for i in range(int(input())):a,b=b,a+b
print(a)
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 比較演算
print("Yes" if sorted(input())<sorted(input())[::-1] else "No")
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))
print("Heisei" if input()<="2019/04/30" else "TBD")
1.7 論理演算
Y=int(input())
print("YES" if Y%4==0 and Y%100!=0 or Y%400==0 else "NO")
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")
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")
a,b=map(int,input().split())
print("Yay!" if a<9 and b<9 else ":(")
1.8 条件式
if文
Y=int(input())
print("YES" if Y%4==0 and Y%100!=0 or Y%400==0 else "NO")
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 "!")
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")
a=int(input())
b=int(input())
print("GREATER" if a>b else "LESS" if a<b else "EQUAL")
print("ABC" if input()=="1" else "chokudai")
n=int(input())
print("Bad" if n<60 else "Good" if n<90 else "Great" if n<100 else "Perfect")
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")
x,y=map(int,input().split())
print("Better" if x<y else "Worse")
print("ABC" if int(input()) < 1200 else "ARC")
a,b=input().split()
print("H" if a==b else "D")
x,a,b=map(int,input().split())
print("dangerous" if x<b-a else "safe" if a<b else "delicious")
x,t=map(int,input().split())
print("0" if x-t<0 else x-t)
a,b,c=map(int,input().split())
print(a if b==c else b if a==c else c)
x,y=input().split()
print("<" if x<y else "=" if x==y else ">")
a,b,c,d=map(int,input().split())
print("Left" if a+b>c+d else "Balanced" if a+b==c+d else "Right")
a,b,c=map(int,input().split())
print("Yes" if a+b>=c else "No")
a,b=map(int,input().split())
print(a-1 if a>b else a)
print("ABC" if int(input())<1000 else "ABD")
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()))
b=input()
print("A" if b=="T" else "T" if b=="A" else "G" if b=="C" else "C")
if/break/else文
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
S=map(str,input().split("+"))
ans=0
for s in S:
if "0" not in s:ans+=1
print(ans)
print(sum("r" in input() for i in range(12)))
input()
l=map(str,input().split())
print("Three" if len(set(l))==3 else "Four")
input()
print("Four" if "Y" in input() else "Three")
print("Yes" if input() in input()*2 else "No")
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)
print("YES" if input() in "369" else "NO")
ABC049 A - 居合を終え、青い絵を覆う / UOIAUAI
print("vowel" if input() in "aiueo" else "consonant")
print("Yes" if "9" in input() else "No")
print("No" if "2" in input() else "Yes")
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")
a,b,c,d=input()
print("Yes" if a==b==c or b==c==d else "No")
a,b,c,d=input()
print("Yes" if a==b==c or b==c==d else "No")
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())
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)
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()
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)
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)
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
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)
H,B=map(float,input().split())
print(H**2*B/1e4)
2.3 文字列(str)
文字列の結合
print("foo"+"bar")
foobar
a,b=input().split()
print(2*int(a+b))
print(input()+"pp")
print(input()+"s")
print("ABC"+input())
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
s=input()
print(s[0]+str((len(s)-2))+s[-1])
s=input()
n=int(input())-1
print(s[n//5]+s[n%5])
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())
a,b,c=input().split()
print("YES" if a[-1]==b[0] and b[-1]==c[0] else "NO")
S="XACABABAABABA"
x,y=map(int,input().split())
print("Yes" if S[x]==S[y] else "No")
n=input()
print("Yes" if n[0]==n[2] else "No")
n=input()
print("Yes" if n[0]==n[1]==n[2] or n[1]==n[2]==n[3] else "No")
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]]))
print(*input().split()[::-1])
n=input()
print("Yes" if n==n[::-1] else "No")
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))
print("Yes" if sorted(input())<sorted(input())[::-1] else "No")
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
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]]))
x,y=input().split()
print("<" if x<y else "=" if x==y else ">")
文字列のコピー
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)
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.
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.
s=input()
print(s[0].upper()+s[1:].lower())
- capitalize:文字列の先頭文字を大文字に変換する
Text="this is a pen."
print(Text.capitalize())
This is a pen.
print("abcd".capitalize())
- title:各単語の先頭文字を大文字に変換する
Text="this is a pen."
print(Text.title())
This Is A Pen.
大文字小文字判定
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']
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
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)
s=input()
print(len(s)-s[::-1].index("Z")-s.index("A"))
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")
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)
print('0ABCDE'.index(input()))
print(["A","B","C","D","E"].index(input())+1)
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
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))
n=int(input())
a=list(map(int,input().split()))
print(-(-sum(a)//(n-a.count(0))))
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")
a,b=map(int,input().split())
s=input()
print("Yes" if s[a]=="-" and s.count("-")==1 else "No")
print(input().count("1"))
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
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])
s=input()
k=int(input())
print(len(set(s[i:i+k] for i in range(len(s)-k+1))))
s=input()
print("no" if len(s)-len(set(s)) else "yes")
print(len(set([int(input()) for _ in range(int(input()))])))
print("DIFFERENT" if len(set(input()))!=1 else "SAME")
ABC046 A - AtCoDeerくんとペンキ / AtCoDeer and Paint Cans
print(len(set(input().split())))
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']
input()
print(input()[:-1].lower().split().count("takahashikun"))
S=input()
A,B,C,D=map(int,input().split())
print(S[:A]+'"'+S[A:B]+'"'+S[B:C]+'"'+S[C:D]+'"'+S[D:])
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])
s=input()
print(s[0].upper()+s[1:].lower())
r=sorted(int(input())**2 for i in range(int(input())))[::-1]
print((sum(r[::2])-sum(r[1::2]))*355/113)
s=input()
k=int(input())
print(len(set(s[i:i+k] for i in range(len(s)-k+1))))
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()
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]))
print(input()[::2])
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)
n=int(input())
s=input()
print(max(len(set(s[:i])&set(s[i:])) for i in range(n)))
s=input()
print(min(abs(int(s[i:i+3])-753) for i in range(len(s))))
n=int(input())
p=sorted([int(input()) for i in range(n)])
print(p[-1]//2+sum(p[:-1]))
input()
L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")
print("NO" if int(input()[::2])%4 else "YES")
print(sum(sorted(map(int,input().split()))[:2]))
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]
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]))
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))
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))
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)
- タプル
( )はイミュータブルで要素の書き換えができません。リストと同様、インデックス(番号)で要素にアクセスします。
要素の探索
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)
- 辞書
{ }はミュータブルでリストに似ていますが、要素へのアクセスは値に一意なキーで行います。
要素の探索
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()])
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())
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")
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'}
N=int(input())
s=set()
for i in range(N):s^={input()}
print(len(s))
print(eval(input().replace(' ','^')))
print(eval(input().replace(" ","^")))
部分集合
A \subseteq B
print({"a","b"}<={"a","b","c"})
True
print({"a","d"}<={"a","b","c"})
False
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']
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
print(sum("r" in input() for i in range(12)))
n,s,t=map(int,input().split())
w=c=0
for i in range(n):
w+=int(input())
c+=s<=w<=t
print(c)
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))
a,b=map(int,input().split())
print(a-(a>b))
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
n=int(input())
x=""
while n!=0:
x=str(n%2)+x
n=-(n//2)
print(0 if x=="" else x)
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
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
N=int(input())
A=list(map(int,input().split()))
print(*A[::-2],*A[N%2::2])
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
s=input()
print(s[0]+str((len(s)-2))+s[-1])
print(max(input(),input(),key=len))
リスト
s=input()
print("no" if len(s)-len(set(s)) else "yes")
print("DIFFERENT" if len(set(input()))!=1 else "SAME")
ABC046 A - AtCoDeerくんとペンキ / AtCoDeer and Paint Cans
print(len(set(input().split())))
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])
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])
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]))
input()
a=sorted(map(int,input().split()))
print(a[-1]-a[0])
X=[int(input()) for i in range(3)]
for x in X:print(3-sorted(X).index(x))
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")
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]]
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")
input()
L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")
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))
l=[int(input()) for _ in range(int(input()))]
print(sum(l)-int(max(l)/2))
print(max(map(int,input().split())))
print(max(input(),input(),key=len))
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))
a,b,c,d=map(int,input().split())
print(max(a*b,c*d))
a,b=map(int,input().split())
print(max(a+b,a-b,a*b))
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))
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
n=int(input())
print(min(int(input()) for i in range(n)))
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)
n,m,x=map(int,input().split())
s=sum(int(i)<x for i in input().split())
print(min(s,m-s))
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)
a,b,c=map(int,input().split())
print(c//min(a,b))
n,x=map(int,input().split())
print(min(x-1,n-x))
a,b,c=map(int,input().split())
print(min(a+b,b+c,c+a))
n,a,b=map(int,input().split())
print(min(n*a,b))
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))
a,b,c=map(int,input().split())
print(min(c,b//a))
4.4 合計値
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)))
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]))
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]))
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")
print(sum(eval(input().replace(' ','*')) for i in range(3))//10)
x=sum(map(int,input()[::2]))
print(x if x<10 else "error")
print(sum(sorted(map(int,input().split()))[:2]))
数字和
- 数字和:digit sum
x=1234
print(sum(map(int,x)))
10(=1+2+3+4)
n=input()
print("No" if int(n)%sum(map(int,n)) else "Yes")
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)
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")
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))
s=input()
print(min(abs(int(s[i:i+3])-753) for i in range(len(s))))
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']
print(sum(eval(input().replace(' ','*')) for i in range(3))//10)
print(eval(input().replace(' ','^')))
print(eval(input().replace(" ","-"))+1)
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)
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}
print("\n".join(input() for _ in range(4))[::-1])
for i in reversed([input() for i in range(4)]):
print(i[::-1])
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))
順位行列
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 グリッド
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")
h,w=map(int,input().split())
for i in range(h):
s=input()
print(s+"\n"+s)
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')
h,w=map(int,input().split())
print("#"*(w+2))
for i in range(h):print("#"+input()+"#")
print("#"*(w+2))
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)
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 数列
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)
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)))
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)
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]))
l=sorted(map(int,input().split()))
a=2*l[2]-l[1]-l[0]
print((a+3)//2 if a%2 else a//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 再帰
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 グラフ
N=int(input())
K=int(input())
print("YES" if K<=N//2 else "NO")
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}))
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)
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)
input()
a=input().split()
input()
a+=input().split()
print("YES" if len(a)==len(set(a)) else "NO")
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つの自然数の最大公約数を求める手法
a,b=12,8
x,y=max(a,b),min(a,b)
while y!=0:x,y=y,x%y
print(x)
4
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
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
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))
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(動的計画法)
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])
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])
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(深さ優先探索)
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"))
- 未解答
BFS
- BFS:Breadth First Search(幅優先探索)
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
- 未解答
ABC040 D - 道路の老朽化対策について
ABC120 D - Decayed Bridges
ABC075 C - Bridge
ABC054 C - One-stroke Path
ABC015 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)
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)
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)
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)))
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))
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))
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
貪欲法
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")
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)
最大フロー
- 未分類
エラトステネスのふるい
- 未解答
ワーシャル–フロイド法
- 未解答
クラスカル法/プリム法
- 未解答
第7章 計算量観点
剰余
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)
ans=1
n=int(input())
for i in range(1,n+1):
ans*=i
print(ans%(10**9+7))
ソート
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="")
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="")
つるかめ算
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")
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")
いもす法
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]))
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()
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="")
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))
- 未分類
累積和
- 累積和: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]
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)))
N=int(input())
A=list(map(int,input().split()))
print(min(abs(sum(A[:i])-sum(A[i:])) for i in range(1,N)))
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)
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])
- 未分類
二分探索
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)
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)
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)
- 未分類
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])
条件式によるループ回数削減
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)
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)
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)
import math
N,M=map(int,input().split())
print(max(2-abs(N-M),0)*math.factorial(N)*math.factorial(M)%(10**9+7))
a,b,c=0,0,1
for i in range(int(input())-1):
a,b,c=b,c,(a+b+c)%10007
print(a)
a,b,c=0,0,1
for i in range(int(input())-1):
a,b,c=b,c,a+b+c
print(a%10007)
print(eval(input().replace(" ","*"))%(10**9+7))
方程式
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]))
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))
部分数列の総和
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)))
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)))
キュー
N=int(input())
A=list(map(int,input().split()))
print(*A[::-2],*A[N%2::2])
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章 数学観点
和差算
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()))
数直線
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)
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)
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))
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:]))
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)
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))
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")
座標
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))
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())))
x1,y1,x2,y2=map(int,input().split())
x=x2-x1
y=y2-y1
print(x2-y,y2+x,x1-y,y1+x)
面積
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)])
a,b,c=map(int,input().split())
print(a*b//2)
a,b,c=map(int,input().split())
print(2*(a*b+b*c+c*a))
a,b,h=[int(input()) for i in range(3)]
print((a+b)*h//2)
a,b,c,d=map(int,input().split())
print(max(a*b,c*d))
倍数
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]
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])
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
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")
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")
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) × ... $ となる。
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
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
from itertools import combinations
S=map(int,input().split())
print(sorted(map(sum,combinations(S,3)))[-3])
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)]))
K=int(input())
print((K//2)*((K+1)//2))
経路
\frac{(width+height -2)!}{(width-1)!(height -1)!}
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 - 乱数生成
期待値
n,m=map(int,input().split())
print((1900*m+100*(n-m))*2**m)
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
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
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))
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
print(int(int(input())**.5)**2)
相加相乗平均
\frac{a+b}{2} ≧ \sqrt{ab}
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|
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章 カテゴリ観点
日時
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))
n=int(input())
print("%02d:%02d:%02d"%(n//3600,(n%3600)//60,n%60))
a,b=map(int,input().split())
print(a-1 if a>b else a)
print("Heisei" if input()<="2019/04/30" else "TBD")
時計
n,m=map(int,input().split())
a=abs(n%12*30-5.5*m)
print(min(a,360-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)
宝くじ
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))
ゾロ目
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
print("HD"[len(set(input()))%2])
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
x,y=input().split()
print("=><"[x>y or -(x<y)])
a,b,c,d=map(int,input().split())
print(['Balanced','Left','Right'][(a+b>c+d)-(a+b<c+d)])
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
^
"""
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)
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
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
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()]))
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())))
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()))
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)
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)
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")
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
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]
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
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
from itertools import product
[print("".join(i)) for i in product("abc",repeat=int(input()))]
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)
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
from itertools import combinations
S=map(int,input().split())
print(sorted(map(sum,combinations(S,3)))[-3])
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))
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")
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)
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
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
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
print(eval(input().replace(" ","**2*"))/1e4)
print(eval(input().replace(" ","*"))%(10**9+7))
print(sum(1-eval(input().replace(" ","-")) for _ in range(int(input()))))
print("NO" if eval(input().replace(" ","%")) else "YES")
print(sum(eval(input().replace(' ','*')) for i in range(3))//10)
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']
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]]
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)))
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
S=input()[0:12]
key="WBWBWWBWBWBW"*2
ans=["Do","","Re","","Mi","Fa","","So","","La","","Si"]
print(ans[(key.find(S))])
s=input()
print(s.rfind("Z")-s.find("A")+1)
isdecimal/isdigit/isnumeric/isalpha/isalnum
- isdecimal:全ての文字が十進数字なら真、そうでなければ偽(半角・全角のアラビア数字が真)
s="1234567890"
print(s.isdecimal())
True
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
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']
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"))
print(input().replace("Left","<").replace("Right",">").replace("AtCoder","A"))
print("YES" if input().replace("ch","").replace("o","").replace("k","").replace("u","")=="" else "NO")
print(2*int(input().replace(" ","")))
print(eval(input().replace(" ","*"))%(10**9+7))
s=input()
print("AC" if "C" in s[2:-1] and "A" in s and s[1:].replace("C","",1).islower() else "WA")
print(sum(eval(input().replace(' ','*')) for i in range(3))//10)
print(eval(input().replace(' ','^')))
print("2018"+input()[4:])
print(eval(input().replace(" ","-"))+1)
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
print(input().translate(str.maketrans("ODIZSB","001258")))
10.4 正規表現
- 正規表現:Regular Expression
マッチ
- findall:マッチする部分すべてをリストで返す
import re
print(max(map(len,re.findall("[ACGT]*",input()))))
import re
print(*re.findall("[0-9]+",input()))
- match:文字列の先頭がパターンにマッチするかを調べる
import re
print("YES" if re.match("^(dream|dreamer|erase|eraser)+$",input()) else "NO")
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")
import re
print("AC" if re.match("^A[a-z]+C[a-z]+$",input()) else "WA")
- split:stringを出現したpatternで分割する
import re
print(max(map(len,re.split("[^ACGT]",input()))))
検索
- search:先頭に限らずパターンにマッチするかを調べる
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:マッチした部分を置換する
import re
print(re.sub("\D","",input()))
import re
print(re.sub("[aiueo]","",input()))
import re
print("NO" if re.sub(r"ch|o|k|u","",input()) else "YES")
import re
print(re.sub("[aiueo]","",input()))
10.5 Lambda式
x=lambda:int(input())
print((x()+x())*x()//2)
a,b=map(lambda x:(int(x)+13)%15,input().split())
print("Alice" if a>b else "Bob" if a<b else "Draw")
i=lambda:int(input())
print((i()-i())%i())
f=lambda:min(int(input()),int(input()))
print(f()+f())
用語
AtCoder用語集
ハーシャッド数
- 各位の数字和が元の数の約数にある自然数
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}
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}
a,b,c=0,0,1
for i in range(int(input())):
a,b,c=b,c,a+b+c
print(a)
参考
参照ページ
- 2進数・8進数・10進数・16進数の相互変換についてまとめてみた
- Pythonビギナーズガイド(変数・配列編)
- pythonで三項演算子のネスト
- 【Python入門】いまさらだけどパイソニスタとして必要な文法を網羅してみた
- 【Python入門】for文でのin演算子の使い方とは?
- Python ビット演算 超入門
- Pythonの集合演算
- Python リストのメソッド
- pythonの内包表記を少し詳しく
- 【Python】ソート
- Pythonで2次元配列の重複行を一発で削除する
- Python標準で転置行列
- Pythonのリスト、タプル、辞書
- [Python]リスト、タプル、辞書、集合の違い
- 正規表現操作
- Pythonでの正規表現の使い方
- Pythonの正規表現モジュールreの関数match、search、sub
- itertoolsによる順列、組み合わせ、直積のお勉強
- 組み込み関数
- [python] いろいろな文字種のリストを作成
- Pythonで文字列が数字か英字か英数字か判定・確認
- 高階関数の使い方!Pythonでreduceを使う方法【初心者向け】
- Pythonで大文字・小文字を操作する文字列メソッド一覧
- Pythonでタプルやリストをアンパック(複数の変数に展開して代入)
- Pythonで競プロやるときによく書くコードをまとめてみた
- Python入門 - 演算子
- Python3.xのアスタリスク逆引き
- [初心者向け] プログラムの計算量を求める方法
- 計算量オーダーの求め方を総整理! 〜 どこから log が出て来るか 〜
- Pythonで二分探索する公式ライブラリ
関連ページ
AtCoder情報
- AtCoderでの勉強の仕方(コンテスト編)
- AtCoder に登録したら次にやること ~ これだけ解けば十分闘える!過去問精選 10 問
- AtCoder コンテストについての tips
- AtCoder に登録したら解くべき精選過去問 10 問 をPythonで解いてみた
コーディング規約
PEP 8 -- Style Guide for Python Code
[Pythonコーディング規約]PEP8を読み解く