はじめに
AtCoder の問題を Python で解いています。問題の復習と自分の技術力を分析するために、問題を解いて得られた知見をメモとして残しています。周りの方から「知見を共有して欲しい」「公開することでコードレビューされて、技術力がより高まるよ」などの意見を頂いたため、本記事を執筆する運びとなりました。
本記事について
本記事について説明します。
構成
本記事では 分類観点 を定義し、分類観点ごとに問題を分類しています。各分類観点では、サンプルコード(入力 / 実行結果)と 解答例 を記載しています。サンプルコード(入力 / 実行結果)と 解答例 は下記の通りです。
項目 | 項目内容 |
---|---|
サンプルコード | 問題から得られた知見と検証によって得られた知見を整理したコード |
入力 | サンプルコードの入力例 |
実行結果 | サンプルコードの実行結果 |
解答例 | AtCoder で AC になったコード |
解答例(TLE) | AtCoder で TLE になったコード |
分類観点の定義
分類観点の定義は下記の通りです。1つの問題から複数の観点で分類できる問題は、複数の観点に分類します。
章 | 観点 | 観点内容 |
---|---|---|
第1章 | 入出力観点 | 入出力を知っていれば解ける問題 |
第2章 | 演算観点 | 演算を知っていれば解ける問題 |
第3章 | 制御フロー観点 | 制御フローを知っていれば解ける問題 |
第4章 | 組み込み型観点 | 組み込み型を知っていれば解ける問題 |
第5章 | 組み込み関数観点 | 組み込み関数を知っていれば解ける問題 |
第6章 | モジュール観点 | モジュールを知っていれば解ける問題 |
第7章 | データ構造観点 | データ構造を知っていれば解ける問題 |
第8章 | アルゴリズム観点 | アルゴリズムを知っていれば解ける問題 |
第9章 | 計算量観点 | 計算量を工夫すれば解ける問題 |
第10章 | 数学観点 | 数学的知見を知っていれば解ける問題 |
第11章 | カテゴリ観点 | カテゴリ特有の解き方を知っていれば解ける問題 |
- | 参考 | - |
分類する問題の範囲
分類する問題の範囲は下記の通りです。ABC-C問題 と ARC-A問題 は一部の問題が同じです。同じ問題の場合、ABC-C問題 として分類します。
- ABC-A問題(ABC001 - ABC158)
- ABC-B問題(ABC001 - ABC158)
- ABC-C問題(ABC001 - ABC158)
- ARC-A問題(ARC001 - ARC103)
分類する対象の問題
本記事では、上記分類範囲で示したすべての問題が記載されているわけではありません。私が上記分類観点で知見が得られた問題のみを記載しています。
バージョン / 言語
サンプルコードは Python の下記バージョンで動作することを確認しています。
Python 3.6.4
解答例は AtCoder の下記言語で AC になることを確認しています。
Python3 (3.4.3)
コーディング方針
コーティングは下記方針で行っています。また、Python のコードスタイルガイドとして PEP 8 があります。
- インデントは空白4つを使う
- コード1行の長さは定義しない
- 演算子の前後、コンマの後、括弧類のすぐ内側に空白を入れない
- import は行を分けて定義する
- クォーテーションはダブルクォーテーションで統一する
- 複数の変数を1行で定義できる場合は1行で定義する
- 変数名は AtCoder の問題文を参考にする
- 命名規則はない
- 自分の直感に合うコーディングをする
更新方針
本記事は下記方針で記事を更新する予定です。更新情報は 編集履歴 より確認をお願いします。
- 新規問題の分類
- 分類の詳細化
- AtCoder言語アップデートの対応(AtCoderの言語アップデートに関して - AtCoder)
知的財産権
本記事に記載しているコードはすべて私が作成したコードです。また、AtCoder における知的財産権は下記の通りです。
知的財産権
1.本サービスに対して投稿されたプログラムの所有権と著作権は、そのプログラムを作成したユーザに帰属します
2.本サービスを構成する文章、画像、プログラムその他のデータ等についての一切の権利(所有権、知的財産権、肖像権、パブリシティー権等)は、ユーザ自身が作成したものを除き、弊社又は当該権利を有する第三者に帰属しています
3.ユーザ自身が作成した著作物を本サービスを通じて掲載した場合、弊社が宣伝告知等に利用することを許諾するものとします。また、かかる使用に際して、当該ユーザは著作者人格権を行使しないものとします
本記事に記載しているコードを私的利用する場合、自由に活用して頂いて構いません。また、作成したコードは GitHub で公開しています。コードを転用する / 商業利用する場合は、メールで事前にご相談をお願い致します。
学習方法の特性上「他人のコードに酷似している」ことがあります。気分を害される方がいましたら、相談の上で引用元の記載 / 記事の更新 / 文章の削除等に対応しますので、ご連絡をお願い致します。
最後に
サービスを提供している AtCoder株式会社 と、交流している 競技プログラマ の方々に感謝を致します。
編集履歴
- 初版公開
1.1版 編集内容
1.2版 編集内容
1.3版 編集内容
1.4版 編集内容
1.5版 編集内容
1.6版 編集内容
2.0版 編集内容
第1章 入出力観点
1.1 出力
整数(int)
整数を出力する
print(10)
10
整数を変数に格納して出力する
x=20
print(x)
20
int() は整数を返す
print(int(2.9))
2
浮動小数点数(float)
浮動小数点数を出力する
print(2.9)
2.9
浮動小数を変数に格納して出力する
x=3.5
print(x)
3.5
float() は浮動小数点数を返す
print(float(2))
2.0
文字列(str)
- テキストシーケンス型
- str
- str():文字列を返す
文字列を出力する
print("Hello World!")
Hello World!
文字列を変数に格納して出力する
s="Hello World!"
print(s)
Hello World!
文字列の変数のインデックスを指定して文字を出力する
s="Hello World!"
print(s[0])
print(s[11])
H
!
s=input()
print(s[0]+str((len(s)-2))+s[-1])
a,*b,c=input()
print(a+str(len(b))+c)
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(Lists)
[1, 2, 3, 4, 5]
1次元リストの各要素を出力する
Lists=[1,2,3,4,5]
for List in Lists:
print(List)
1
2
3
4
5
1次元リストの各要素を改行しない(アンパック)で出力する
Lists=[1,2,3,4,5]
print(*Lists)
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
ABC042 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))
K,X=map(int,input().split())
print(*[x for x in range(X-K+1,X+K)])
K,X=map(int,input().split())
print(*list(range(X-K+1,X+K)))
K,X=map(int,input().split())
print(*range(X-K+1,X+K))
ABC148 B - Strings with the Same Length
N=input()
S,T=input().split()
print(*[s+t for s,t in zip(S,T)],sep="")
タプル(tuple)
x=1,2,3
print(x)
(1, 2, 3)
N,Y=map(int,input().split())
answer=-1,-1,-1
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:
answer=x,y,z
break
else:
continue
break
print(*answer)
区切り文字の指定
- print():キーワード引数 sep を指定する
指定がないと 半角スペース で区切る
a=1
b=2
c=3
print(a,b,c)
1 2 3
print(*input().split(","))
改行 を指定する
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="")
ABC148 B - Strings with the Same Length
N=input()
S,T=input().split()
print(*[s+t for s,t in zip(S,T)],sep="")
Tenka1 Programmer Beginner Contest 2019 B - e*** *****e *ee* **e**
input()
S=input()
k=int(input())
for s in S:print(s if s==S[k-1] else "*",end="")
末尾文字の指定
- print():キーワード引数 end を指定する
指定がないと 改行する
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 入力
- input():入力から1行を読み込み、文字列に変換して(末尾の改行を除いて)返す
- map():function の結果を返しながら、全ての要素に適用する iterator を返す
- str.split():文字列を区切った単語のリストで返す
- リスト内包表記
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")
a,b,c,d=input()
print("Good" if a!=b and b!=c and c!=d else "Bad")
a,b,c,d=input()
print("Good" if a!=b!=c!=d else "Bad")
1行 / 複数列
整数を複数の変数に格納する
1 2
a,b=map(int,input().split())
print(a)
print(b)
1
2
a,b=map(int,input().split())
print(b,a)
S,T=input().split()
print(T+S)
文字列を複数の変数に格納する
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))
複数行 / 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)))))
N=int(input())
p=[int(input()) for i in range(N)]
print(sum(p)-max(p)//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']
複数行 / 複数列
複数のリストに格納する(入力時に行数(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)
第2章 演算観点
2.1 算術演算
演算子 | 記述例 | 意味 |
---|---|---|
+ | a+b | 加算 |
- | a-b | 減算 |
* | a*b | 乗算 |
** | a**b | べき乗 / べき根 |
/ | a/b | 除算 |
// | a//b | 小数点切り捨て除算 |
% | a%b | 剰余 |
加算
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)
減算
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)
a,b,c,d,e,k=[int(input()) for i in range(6)]
print("Yay!" if abs(a-e)<=k else ":(")
A,B,C=map(int,input().split())
d=C-(A-B)
print(d if d>0 else 0)
A,B,C=map(int,input().split())
print(max(0,C-A+B))
乗算
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))
H,W=map(int,input().split())
h,w=map(int,input().split())
print((H-h)*(W-w))
K,X=map(int,input().split())
print("Yes" if 500*K>=X else "No")
階乗
- math.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)
べき乗
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()))
print(3*int(input())**2)
print(int(input())**3)
print(int(input())**2)
べき根
print(4**0.5)
2.0
print(4**.5)
2.0
print(4**(1/2))
2.0
print(8**(1/3))
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")
除算
print(6/3)
2.0
N=int(input())
v=sorted(map(int,input().split()))
value=v[0]
for i in range(1,N):
value=(value+v[i])/2
print(value)
ABC138 B - Resistors in Parallel
input()
A=map(int,input().split())
print(1/sum(1/a for a in A))
小数点切り捨て除算
print(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)))
N,A,B=map(int,input().split())
div=N//(A+B)
mod=N%(A+B)
print(div*A+min(mod,A))
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(" ","/")))
a,p=map(int,input().split())
print((3*a+p)//2)
N=int(input())
print("0.5" if N%2==0 else ((N//2)+1)/N)
N=int(input())
print((N-N//2)/N)
H,A=map(int,input().split())
print(H//A if H%A==0 else H//A+1)
H,A=map(int,input().split())
print((H+A-1)//A)
小数点切り上げ除算
- math.ceil():引数以上の最小の整数を返す
import math
print(math.ceil(5/3))
2
ABC123 C - Five Transportations
import math
n=int(input())
l=[int(input()) for i in range(5)]
print(math.ceil(n/min(l))+4)
import math
N=int(input())
A=list(map(int,input().split()))
print(math.ceil(sum(A)/(N-A.count(0))))
from itertools import permutations
import math
menu=5
times=[int(input()) for i in range(menu)]
orders=list(permutations(times,menu))
minimum=sum(math.ceil(time/10)*10 for time in times)
for order in orders:
total=order[0]
for i in range(1,menu):
total+=math.ceil(order[i]/10)*10
minimum=min(minimum,total)
print(minimum)
import math
N,D=map(int,input().split())
print(math.ceil(N/(D*2+1)))
import math
A,B=map(int,input().split())
print(1+math.ceil((B-A)/(A-1)))
import math
A,B=map(int,input().split())
print(math.ceil(B/A))
import math
a,b=map(int,input().split())
print(math.ceil((a+b)/2))
import math
N=int(input())
print(math.ceil(N/2))
N=int(input())
print(N//2+N%2)
N=int(input())
print((N+1)//2)
剰余
print(7%3)
1
N=int(input())
ans=N
for i in range(N+1):
cnt=0
t=i
while t>0:
cnt+=t%6
t//=6
j=N-i
while j>0:
cnt+=j%9
j//=9
ans = min(ans,cnt)
print(ans)
ABC133 C - Remainder Minimization 2019
L,R=map(int,input().split())
if R-L>=2019:
minimum=0
else:
left,right=L%2019,R%2019
minimum=2018**2
for i in range(left,right+1):
for j in range(i+1,right+1):
minimum=min(minimum,i*j%2019)
print(minimum)
L,R=map(int,input().split())
left,right=L%2019,R%2019
print(0 if R-L>=2019 else min(i*j%2019 for i in range(left,right+1) for j in range(i+1,right+1)))
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())
S=input()
print("".join(chr(65+(ord(s)-65+N)%26) for s in S))
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)
A,B=map(int,input().split())
print((A+B)//2 if (A+B)%2==0 else "IMPOSSIBLE")
H,A=map(int,input().split())
print(H//A if H%A==0 else H//A+1)
H,A=map(int,input().split())
print((H+A-1)//A)
N=int(input())
print(N//2+N%2)
N=int(input())
print((N+1)//2)
N,A,B=map(int,input().split())
div=N//(A+B)
mod=N%(A+B)
print(div*A+min(mod,A))
2.2 代入文
a,b=1,2
print(a,b)
a,b=b,a
print(a,b)
1 2
2 1
n=int(input())
a,b,c=0,0,1
for i in range(n-1):
a,b,c=b,c,(a+b+c)%10007
print(a)
N=int(input())
a,b=2,1
for i in range(N):
a,b=b,a+b
print(a)
2.3 累算代入文
演算子 | 記述例 | 等式 |
---|---|---|
+= | a+=b | a=a+b |
-= | a-=b | a=a-b |
*= | a*=b | a=a*b |
**= | a**=b | a=a**b |
/= | a/=b | a=a/b |
//= | a//=b | a=a//b |
%= | a%=b | a=a%b |
2.4 論理演算
演算子 | 記述例 | 意味 |
---|---|---|
and | a and b | a も b も真であれば真 |
or | a or b | a または b が真であれば真 |
not | not a | a が偽であれば真 |
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")
N=int(input())
A=list(map(int,input().split()))
flag=True
for i in range(N):
if A[i]%2==0 and A[i]%3!=0 and A[i]%5!=0:flag=False
print("APPROVED" if flag else "DENIED")
input()
A=list(map(int,input().split()))
print("APPROVED" if all([a%2!=0 or a%3==0 or a%5==0 for a in A]) else "DENIED")
input()
A=list(map(int,input().split()))
print("APPROVED" if all(a&1 or a%3==0 or a%5==0 for a in A) else "DENIED")
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 ":(")
Tenka1 Programmer Beginner Contest 2019 A - On the Way
a,b,c=map(int,input().split())
print("Yes" if a<c<b or b<c<a else "No")
2.5 比較演算
演算子 | 記述例 | 意味 |
---|---|---|
== | a==b | a が b と等しい |
!= | a!=b | a が b と等しくない |
> | a>b | a が b より大きい |
>= | a>=b | a が b 以上 |
< | a<b | a が b より小さい |
<= | a<=b | a が b 以下 |
s=sorted(input())
t=sorted(input())[::-1]
print("Yes" if s<t else "No")
S=input()
print("Heisei" if S<="2019/04/30" else "TBD")
2.6 所属検査演算
演算子 | 記述例 | 意味 |
---|---|---|
in | a in b | a が b に含まれる |
not in | a not in b | a が b に含まれない |
2.7 ブール演算
演算子 | 記述例 | 意味 |
---|---|---|
or | x or y | x が偽なら y、そうでなければ x |
and | x and y | x が偽なら x、そうでなければ y |
not | not x | x が偽なら True、そうでなければ False |
ブール値を数値に変換
print(int(True))
1
print(int(False))
0
print(-(3>2))
-1
print(-(3<2))
0
print(True+0)
1
print(False+0)
0
W,H,x,y=map(int,input().split())
print(W*H/2,int(W==2*x and H==2*y))
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)
X,A=map(int,input().split())
print(10*(X>=A))
2.8 ビット演算
演算子 | 記述例 | 意味 |
---|---|---|
& | a&b | a と b のビット単位の AND を与える |
^ | a^b | a と b のビット単位の XOR(排他的OR)を与える |
| | a|b | a と b のビット単位の OR を与える |
~ | ~a | a(整数)のビット単位反転を与える |
演算 | 結果 |
---|---|
bin(0b1010&0b0110) | 0b10 |
bin(0b1010^0b0110) | 0b1100 |
bin(0b1010|0b0110) | 0b1110 |
print(bin(0b1010&0b0110))
print(bin(0b1010^0b0110))
print(bin(0b1010|0b0110))
0b10
0b1100
0b1110
input()
A=list(map(int,input().split()))
print("APPROVED" if all(a&1 or a%3==0 or a%5==0 for a in A) else "DENIED")
ビット単位反転(bitwise invert):x
のビット単位反転は-(x+1)
として定義されている
print(~2)
-3
print(~-4)
3
print(~(5-3))
-3
print(~eval(input().replace(" ","-"))+2)
a,b=map(int,input().split())
print(~-a*~-b)
a,b=map(int,input().split())
print(~-a*~-b)
2.9 シフト演算
演算子 | 記述例 | 意味 |
---|---|---|
<< | a<<b | a を左に b ビットシフト |
>> | a>>b | a を右に b ビットシフト |
左にビットシフト
演算 | 結果 | 10進数 |
---|---|---|
bin(2) | 0b10 | 2 |
bin(2<<1) | 0b100 | 4 |
bin(2<<2) | 0b1000 | 8 |
bin(2<<3) | 0b10000 | 16 |
bin(2<<4) | 0b100000 | 32 |
print(2)
print(2<<1)
print(2<<2)
print(2<<3)
print(2<<4)
print(bin(2))
print(bin(2<<1))
print(bin(2<<2))
print(bin(2<<3))
print(bin(2<<4))
2
4
8
16
32
0b10
0b100
0b1000
0b10000
0b100000
右にビットシフト
演算 | 結果 | 10進数 |
---|---|---|
bin(10) | 0b1010 | 10 |
bin(10>>1) | 0b101 | 5 |
bin(10>>2) | 0b10 | 2 |
bin(10>>3) | 0b1 | 1 |
bin(10>>4) | 0b0 | 0 |
print(10)
print(10>>1)
print(10>>2)
print(10>>3)
print(10>>4)
print(bin(10))
print(bin(10>>1))
print(bin(10>>2))
print(bin(10>>3))
print(bin(10>>4))
10
5
2
1
0
0b1010
0b101
0b10
0b1
0b0
print(["ABC","ARC","AGC"][int(input())//50+8>>5])
print(int(input())**2>>2)
第3章 制御フロー観点
3.1 条件式
if/else文
Y=int(input())
print("YES" if Y%4==0 and Y%100!=0 or Y%400==0 else "NO")
W,H,x,y=map(int,input().split())
print(W*H/2,1) if W==2*x and H==2*y else print(W*H/2,0)
W,H,x,y=map(int,input().split())
print(W*H/2,int(W==2*x and H==2*y))
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")
A,B,K=map(int,input().split())
print(A-K,B) if K<=A else print(0,B-(K-A)) if K<=A+B else print(0,0)
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")
X,A=map(int,input().split())
print("0" if X<A else "10")
a=int(input())
s=input()
print(s if a>=3200 else "red")
S=input()
print("Sunny" if S=="Rainy" else "Cloudy" if S=="Sunny" else "Rainy")
K,X=map(int,input().split())
print("Yes" if 500*K>=X else "No")
N,M=input().split()
print("Yes" if N==M else "No")
S,T=input().split()
A,B=map(int,input().split())
U=input()
print(A-1,B) if S==U else print(A,B-1)
N,R=map(int,input().split())
print(R if N>=10 else R+100*(10-N))
N,R=map(int,input().split())
print(R+100*max(0,10-N))
N=int(input())
print(N//2 if N%2==0 else N//2+1)
Tenka1 Programmer Beginner Contest 2019 A - On the Way
a,b,c=map(int,input().split())
print("Yes" if a<c<b or b<c<a else "No")
if/in文
String="abc"
print("a" in String)
True
String="abc"
print("d" in String)
False
List=["a","b","c"]
print("a" in List)
True
List=["a","b","c"]
print("d" in List)
False
List=["a","b","c"]
print("a" not in List)
False
List=["a","b","c"]
print("d" not in List)
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")
S=input()
print("Good" if S[0]!=S[1]!=S[2]!=S[3] else "Bad")
a,b,c,d=input()
print("Good" if a!=b!=c!=d else "Bad")
A,B=map(int,input().split())
print(A*B if 1<=A<=9 and 1<=B<=9 else "-1")
3.2 繰り返し文
for文
N,M,A,B=map(int,input().split())
for m in range(M):
if N<=A:
N+=B
c=int(input())
N-=c
if N<0:
print(m+1)
break
else:
print("complete")
N,K=map(int,input().split())
t=[int(input()) for i in range(N)]
for i in range(3,N):
if sum(t[i-3:i])<K:
print(i)
break
else:
print(-1)
N,Y=map(int,input().split())
answer=-1,-1,-1
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:
answer=x,y,z
break
else:
continue
break
print(*answer)
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)
N=int(input())
H=list(map(int,input().split()))
base=0
for h in H:
if base>h:
print("No")
break
base=max(base,h-1)
else:
print("Yes")
ABC144 C - Walk on Multiplication Table
N=int(input())
move=10**12
for n in range(1,int(N**.5)+1):
if N%n==0:
move=min(move,N//n+n-2)
print(move)
N,M=map(int,input().split())
sc=[list(map(int,input().split())) for m in range(M)]
for i in range(10**N):
if len(str(i))==N and all(str(i)[s-1]==str(c) for s,c in sc):
print(i)
break
else:
print(-1)
A,B=map(int,input().split())
for money in range(1,1001):
if int(money*0.08)==A and int(money*0.1)==B:
print(money)
break
else:
print(-1)
N=int(input())
for i in range(1,10):
m=N/i
if m.is_integer() and 1<=m<=9:
print("Yes")
break
else:
print("No")
while文
ABC144 C - Walk on Multiplication Table
N=int(input())
move=int(N**.5)
while N%move!=0:
move-=1
print(N//move+move-2)
X=int(input())
while True:
for x in range(2,X):
if X%x==0:
break
else:
print(X)
break
X+=1
X=int(input())
num=2
while num<X:
if X%num==0:
X+=1
num=2
else:
num+=1
print(X)
X=int(input())
for x in range(X,2*X):
for i in range(2,int(x**.5)+1):
if x%i==0:
break
else:
print(x)
break
X=int(input())
for x in range(X,2*X):
flag=True
for i in range(2,int(x**.5)+1):
if x%i==0:
flag=False
break
if flag:
print(x)
exit()
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)
N,K=map(int,input().split())
count=0
while(N>0):
N//=K
count+=1
print(count)
a,b,n=[int(input()) for i in range(3)]
while n%a!=0 or n%b!=0:n+=1
print(n)
第4章 組み込み型観点
4.1 int
print(int(2.9))
2
4.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)
整数判定
-
float.is_integer():浮動小数点数が整数値なら
True
を、そうでなければFalse
を返す
x=1.0
print(x.is_integer())
True
x=1.1
print(x.is_integer())
False
N=int(input())
for i in range(1,10):
m=N/i
if m.is_integer() and 1<=m<=9:
print("Yes")
break
else:
print("No")
4.3 str
- テキストシーケンス型
- str:イミュータブル(変更不可能)なシーケンス
- 文字列メソッド
文字列の結合
print("foo"+"bar")
foobar
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)
S,T=input().split()
print(T+S)
文字列の繰り返し
a,b=input().split()
print(2*int(a+b))
a,b=input().split()
print(a*int(b) if a<b else b*int(a))
a,b=input().split()
print(min(a*int(b),b*int(a)))
print("x"*len(input()))
ABC115 A - Christmas Eve Eve Eve
print("Christmas"+" Eve"*(25-int(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)
S=input()
print("Good" if S[0]!=S[1] and S[1]!=S[2] and S[2]!=S[3] else "Bad")
S=input()
print("Good" if S[0]!=S[1]!=S[2]!=S[3] else "Bad")
S=input()
T=input()
count=0
if S[0]==T[0]:count+=1
if S[1]==T[1]:count+=1
if S[2]==T[2]:count+=1
print(count)
文字列の逆順
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")
文字列の比較
print("Yes" if sorted(input())<sorted(input())[::-1] else "No")
S=input()
print(sum(S[i]!=S[-i-1] for i in range(len(S)//2)))
N=int(input())
S=input()
print(sum(S[i:i+3]=="ABC" for i in range(N-2)))
print("Heisei" if input()<="2019/04/30" else "TBD")
S=input()
T=input()
print(sum(s==t for s,t in zip(S,T)))
文字列の置換
- str.replace():文字列の置換
String="aabbccbbaabbaacc"
print(String.replace("bb","xx"))
aaxxccxxaaxxaacc
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"))
ABC117 A - Entrance Examination
print(eval(input().replace(" ","/")))
文字列のコピー
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))
文字列の判定
String="abc"
[print(chr(i),end=" ") for i in range(ord("a"),ord("z")+1) if chr(i) in String]
a b c
String="abc"
[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 ">")
- str.isdecimal():全ての文字が十進数字なら真、そうでなければ偽(半角・全角のアラビア数字が真)
- str.isdigit():全ての文字が数字なら真、そうでなければ偽(半角・全角のアラビア数字、特殊数字が真)
- str.isnumeric():全ての文字が数を表す文字なら真、そうでなければ偽(半角・全角のアラビア数字、特殊数字、漢数字が真)
- str.isalpha():全ての文字が英字なら真、そうでなければ偽(便宜上「英字」と書いているが、平仮名やカタカナ、漢字なども真)
- str.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
文字列の検索
- str.find() / str.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)
大文字小文字変換
- str.upper():すべての文字列を大文字に変換する
- str.lower():すべての文字列を小文字に変換する
- str.capitalize():文字列の先頭文字を大文字に変換する
- str.title():各単語の先頭文字を大文字に変換する
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.
大文字小文字判定
- str.isupper():大文字判定
- str.islower():小文字判定
s=input()
print("AC" if "C" in s[2:-1] and "A" in s and s[1:].replace("C","",1).islower() else "WA")
文字列の変換
- str.maketrans():変換テーブルを作成する
- str.translate():変換テーブルに基づいてマッピングする
print(input().translate(str.maketrans("ODIZSB","001258")))
4.4 list
- シーケンス型
- list:ミュータブル(変更可能)なシーケンス
- ミュータブルなシーケンス型
要素の追加
- list.append():要素の追加
- ミュータブルなシーケンス型
List=["a","b","c"]
List.append("d")
print(List)
['a', 'b', 'c', 'd']
List=["a","b","c"]
List.append(["d","e"])
print(List)
['a', 'b', 'c', ['d', 'e']]
要素の拡張
- list.extend():要素の拡張
- ミュータブルなシーケンス型
List=["a","b","c"]
List.extend(["d","e"])
print(List)
['a', 'b', 'c', 'd', 'e']
要素の挿入
- list.insert():要素の挿入
- ミュータブルなシーケンス型
List=["a","b","c"]
List.insert(1,"z")
print(List)
['a', 'z', 'b', 'c']
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="")
要素の探索
- list.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)
weather=["Sunny","Cloudy","Rainy"]
S=input()
print(weather[(weather.index(S)+1)%3])
weather=["Sunny","Cloudy","Rainy"]
S=input()
print(weather[weather.index(S)-2])
ABC146 A - Can't Wait for Holiday
week=["SUN","MON","TUE","WED","THU","FRI","SAT"]
print(7-week.index(input()))
[ABC151 A - Next Alphabet](https://atcoder.jp/contests/abc151/tasks/abc151_a
s="abcdefghijklmnopqrstuvwxyz"
print(s[s.index(input())+1])
要素の取り出し
- list.pop():要素の取り出し
- ミュータブルなシーケンス型
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"]
print(List.pop())
print(List)
f
['a', 'b', 'c', 'd', 'e']
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())
要素の取り除き
- list.remove():要素の取り除き
- ミュータブルなシーケンス型
List=["a","b","c","d","e","f"]
List.remove("d")
print(List)
['a', 'b', 'c', 'e', 'f']
List=["a","a","b","b","c","c"]
List.remove("b")
print(List)
['a', 'a', 'b', 'c', 'c']
要素の削除
- del():要素の削除
- ミュータブルなシーケンス型
List=["a","b","c","d","e","f"]
del List[1]
print(List)
['a', 'c', 'd', 'e', 'f']
List=["a","b","c","d","e","f"]
del List[2:4]
print(List)
['a', 'b', 'e', 'f']
List=["a","b","c","d","e","f"]
del List[:]
print(List)
[]
要素の出現回数
- list.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))
ABC124 C - Coloring Colorfully
s=input()
n=s[::2].count("0")+s[1::2].count("1")
print(min(n,len(s)-n))
s=input()
print(min(s[::2].count("0")+s[1::2].count("1"),s[::2].count("1")+s[1::2].count("0")))
import math
N=int(input())
A=list(map(int,input().split()))
print(math.ceil(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)))))
input()
print(input().count("ABC"))
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=input()
print(s.count("+")-s.count("-"))
S=input()
s=list(set(S))
print("Yes" if len(s)==2 and S.count(s[0])==S.count(s[1])==2 else "No")
要素の連結
- str.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))
ABC148 B - Strings with the Same Length
N=input()
S,T=input().split()
print("".join(s+t for s,t in zip(S,T)))
N=input()
S,T=input().split()
print(*[s+t for s,t in zip(S,T)],sep="")
ABC111 A - AtCoder Beginner Contest 999
print("".join(["9" if x=="1" else "1" for x in input()]))
要素のユニーク化
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")
S=input()
s=list(set(S))
print("Yes" if len(s)==2 and S.count(s[0])==S.count(s[1])==2 else "No")
NM=input().split()
print("Yes" if len(set(NM))==1 else "No")
ABC=input().split()
print("Yes" if len(set(ABC))==2 else "No")
S=input()
print("Yes" if len(set(S))!=1 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])
['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:])
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])
N,K=map(int,input().split())
H=sorted(map(int,input().split()))[::-1]
print(sum(H[K:]))
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(sum(p[:-1])+p[-1]//2)
input()
L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")
n=int(input())
w=list(map(int,input().split()))
m=max(w)
for i in range(n):
m=min(m,abs(sum(w[:i+1])-sum(w[i+1:])))
print(m)
S=input()
odd=S[::2]
even=S[1::2]
print("No" if "L" in odd or "R" in even else "Yes")
S=input()
print("No" if "L" in S[::2] or "R" in S[1::2] else "Yes")
N=int(input())
S=input()
print("Yes" if S[:N//2]==S[N//2:] else "No")
N=int(input())
S=input()
print(sum(S[i:i+3]=="ABC" for i in range(N-2)))
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")
要素のソート
List=[[0,1],[1,1],[1,0],[0,0]]
List.sort(key=lambda List:(List[0],List[1]))
for i in List:
print(i)
[0, 0]
[0, 1]
[1, 0]
[1, 1]
List=[[0,1],[1,1],[1,0],[0,0]]
List.sort(key=lambda List:(List[0],-List[1]))
for i in List:
print(i)
[0, 1]
[0, 0]
[1, 1]
[1, 0]
List=[[0,1],[1,1],[1,0],[0,0]]
List.sort(key=lambda List:(-List[0],-List[1]))
for i in List:
print(i)
[1, 1]
[1, 0]
[0, 1]
[0, 0]
List=[[0,1],[1,1],[1,0],[0,0]]
List.sort(key=lambda List:(List[0],List[1]),reverse=True)
for i in List:
print(i)
[1, 1]
[1, 0]
[0, 1]
[0, 0]
n=int(input())
sp=[]
for i in range(n):
s,p=input().split()
sp.append([s,int(p),i+1])
sp.sort(key=lambda sp:(sp[0],-sp[1]))
for i in sp:print(i[2])
4.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)
4.6 dict
要素の探索
print({"Mo":5,"Tu":4,"We":3,"Th":2,"Fr":1,"Sa":0,"Su":0}[input()[:2]])
day=({"Saturday":0,"Sunday":0,"Monday":5,"Tuesday":4,"Wednesday":3,"Thursday":2,"Friday":1})
print(day[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))
N=int(input())
dictionary={}
count=0
for i in range(N):
s="".join(sorted(input()))
if s in dictionary:
dictionary[s]+=1
count+=dictionary[s]
else:
dictionary[s]=0
print(count)
N=int(input())
dictionary={}
count=0
for i in range(N):
s=str(sorted(input()))
if s in dictionary:
dictionary[s]+=1
count+=dictionary[s]
else:
dictionary[s]=0
print(count)
N=int(input())
dictionary={}
count=0
for i in range(N):
s=tuple(sorted(input()))
if s in dictionary:
dictionary[s]+=1
count+=dictionary[s]
else:
dictionary[s]=0
print(count)
import collections
N=int(input())
s=[str(sorted(input())) for i in range(N)]
c=collections.Counter(s)
print(sum((v*(v-1))//2 for v in c.values()))
N=int(input())
S=[input() for i in range(N)]
dictionary={}
for word in S:
if word in dictionary:
dictionary[word]+=1
else:
dictionary[word]=1
for key,value in sorted(dictionary.items()):
if value==max(dictionary.values()):
print(key)
import collections
N=int(input())
S=collections.Counter(input() for i in range(N))
dictionary=sorted(key for key,value in S.items() if value==max(S.values()))
for d in dictionary:
print(d)
import collections
N=int(input())
S=collections.Counter(input() for i in range(N))
maximum=max(S.values())
sort=sorted(key for key,value in S.items() if value==maximum)
for s in sort:
print(s)
N=int(input())
S=[input() for i in range(N)]
dictionary={}
for word in S:
if word in dictionary:
dictionary[word]+=1
else:
dictionary[word]=1
maximum=max(dictionary.values())
for key,value in sorted(dictionary.items()):
if value==maximum:
print(key)
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]))
weather={"Sunny":"Cloudy","Cloudy":"Rainy","Rainy":"Sunny"}
print(weather[input()])
ABC146 A - Can't Wait for Holiday
week={"SUN":7,"MON":6,"TUE":5,"WED":4,"THU":3,"FRI":2,"SAT":1}
print(week[input()])
week=dict(SUN=7,MON=6,TUE=5,WED=4,THU=3,FRI=2,SAT=1)
print(week[input()])
S,T=input().split()
A,B=map(int,input().split())
U=input()
ST={S:A,T:B}
ST[U]-=1
print(ST[S],ST[T])
4.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'}
print(min(set(map(chr,range(97,123)))-set(input())or["None"]))
u={1,2,3}
AB=[int(input()) for i in range(2)]
print(list(u-set(AB))[0])
積
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))
letters="abcdefghijklmnopqrstuvwxyz"
ans=sorted(set(letters)^set(input()))
print("None" if len(ans)==0 else ans[0])
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)
4.8 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}
N,L=map(int,input().split())
taste=range(L,L+N)
print(sum(taste)-min(taste,key=abs))
K,X=map(int,input().split())
print(*list(range(X-K+1,X+K)))
K,X=map(int,input().split())
print(*range(X-K+1,X+K))
第5章 組み込み関数観点
5.1 abs
- abs():絶対値を返す
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")
5.2 all
-
all():iterable の全ての要素が真ならば(もしくは iterable が空ならば)
True
、そうでない場合はFalse
を返す
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")
input()
A=list(map(int,input().split()))
print("APPROVED" if all([a%2!=0 or a%3==0 or a%5==0 for a in A]) else "DENIED")
input()
A=list(map(int,input().split()))
print("APPROVED" if all(a&1 or a%3==0 or a%5==0 for a in A) else "DENIED")
S=input()
print("Good" if all(S[i]!=S[i+1] for i in range(3)) else "Bad")
5.3 any
-
any():iterable のいずれかの要素が真ならば
True
、空ならFalse
を返す
print(any([True,True]))
True
print(any([True,False]))
True
print(any([False,False]))
False
S=input()
print("Bad" if any(S[i]==S[i+1] for i in range(3)) else "Good")
a,b,c=map(int,input().split())
print("YES" if any((a*i)%b==c for i in range(1,b+1)) else "NO")
5.4 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(0x20)
32
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))
5.5 divmod
- divmod():複素数でない2つの数を引数として取り、除算を行ったときの商と剰余からなる対を返す
a,b=divmod(5,2)
print(a)
print(b)
2
1
5.6 enumerate
- enumerate():カウントと iterable 上の iteration によって得られた値を含むタプルを返す
List=["a","b","c"]
for number,alphabet in enumerate(List):
print(number,alphabet)
0 a
1 b
2 c
N=int(input())
A=[(int(a), i) for i,a in enumerate(input().split(),1)]
for a in sorted(A,reverse=True):
print(a[1])
ABC102 C - Linear Approximation
N=int(input())
A=sorted(a-i-1 for i,a in enumerate(map(int,input().split())))
print(sum(abs(a-A[N//2]) for a in A))
5.7 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()))
5.8 len
- len():オブジェクトの長さ(要素の数)を返す
print(len("aiueo"))
5
print(max(["abc","d","ef","ghij"],key=len))
ghij
print(min(["abc","d","ef","ghij"],key=len))
d
N=int(input())
A=set(map(int,input().split()))
print("YES" if N==len(A) else "NO")
s=input()
print("no" if len(s)-len(set(s)) else "yes")
s=input()
print(s[0]+str((len(s)-2))+s[-1])
print("x"*len(input()))
print(max(input(),input(),key=len))
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")
S=input()
s=list(set(S))
print("Yes" if len(s)==2 and S.count(s[0])==S.count(s[1])==2 else "No")
S=input()
print("Yes" if len(set(S))!=1 else "No")
5.9 map
- map():function の結果を返しながら、全ての要素に適用する iterator を返す
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")
5.10 max
- max():iterable の中で最大の要素、または2つ以上の引数の中で最大のものを返す
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))
N=int(input())
p=[int(input()) for i in range(N)]
print(sum(p)-max(p)//2)
A,B,K=map(int,input().split())
print(max(0,A-K),max(0,B-max(0,K-A)))
N,K,M=map(int,input().split())
A=list(map(int,input().split()))
x=max(0,M*N-sum(A))
print(x if x<=K else -1)
N,K,M=map(int,input().split())
A=sum(map(int,input().split()))
x=max(0,M*N-A)
print(x if x<=K else -1)
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")
a,b=map(int,input().split())
print(max(2*a-1,2*b-1,a+b))
A,B,C=map(int,input().split())
print(max(0,C-A+B))
A,B=map(int,input().split())
print(max(A+B,A-B,A*B))
A,B=map(int,input().split())
print(max(0,A-2*B))
A,B=map(int,input().split())
print("-1" if max(A,B)>9 else A*B)
5.11 min
- min():iterable の中で最小の要素、または2つ以上の引数の中で最小のものを返す
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())
B=list(map(int,input().split()))
B+=[max(B)]
A=[0]*N
A[0]=B[0]
for i in range(1,N):
A[i]=min(B[i-1],B[i])
print(sum(A))
N=int(input())
B=list(map(int,input().split()))
B+=[max(B)]
print(sum(min(B[i-1],B[i]) for i in range(N)))
N=int(input())
P=list(map(int,input().split()))
count,minimum=0,max(P)
for i in range(N):
if P[i]<=minimum:
count+=1
minimum=P[i]
print(count)
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)
N,L=map(int,input().split())
taste=[L+i for i in range(N)]
print(sum(taste)-min(taste,key=abs))
N,L=map(int,input().split())
taste=range(L,L+N)
print(sum(taste)-min(taste,key=abs))
a,b=input().split()
print(min(a*int(b),b*int(a)))
N,A,B=map(int,input().split())
div=N//(A+B)
mod=N%(A+B)
print(div*A+min(mod,A))
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))
P,Q,R=map(int,input().split())
print(min(P+Q,Q+R,R+P))
N,A,B=map(int,input().split())
print(min(N*A,B))
5.12 ord/chr
- ord():1 文字の Unicode 文字を表す文字列に対し、その文字の Unicode コードポイントを表す整数を返す
- chr():Unicode コードポイントが整数である文字を表す文字列を返す
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']
N=int(input())
S=input()
print("".join(chr(65+(ord(s)-65+N)%26) for s in S))
print(ord(input())-64)
print(chr(ord(input())+1))
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']
[ABC151 A - Next Alphabet](https://atcoder.jp/contests/abc151/tasks/abc151_a
print(chr(ord(input())+1))
5.13 pow
- pow():べき乗を返す
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)
print(3*pow(int(input()),2))
print(pow(int(input()),3))
print(pow(int(input()),2))
5.14 sorted
- sorted():iterable の要素を並べ替えた新たなリストを返す
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")
N=int(input())
A=list(map(int,input().split()))
sort=[0]*N
for i in range(N):
sort[A[i]-1]+=i+1
print(*sort)
import numpy
N=int(input())
A=list(map(int,input().split()))
print(*numpy.argsort(A)+1)
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))
N=int(input())
A=[int(input()) for i in range(N)]
sort=sorted(A)
x,y=sort[-1],sort[-2]
for a in A:
print(x if a!=x else y)
N=int(input())
A=[int(input()) for i in range(N)]
y,x=sorted(A)[-2:]
for a in A:
print(x if a!=x else y)
N,K=map(int,input().split())
H=sorted(map(int,input().split()))[::-1]
print(sum(H[K:]))
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])
input()
L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")
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)
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)
5.15 sum
- sum():合計を返す
N=int(input())
B=list(map(int,input().split()))
B+=[max(B)]
A=[0]*N
A[0]=B[0]
for i in range(1,N):
A[i]=min(B[i-1],B[i])
print(sum(A))
N=int(input())
B=list(map(int,input().split()))
B+=[max(B)]
print(sum(min(B[i-1],B[i]) for i in range(N)))
N=int(input())
S=input()
print(sum(S[n]!=S[n-1] for n in range(1,N))+1)
import itertools
N=int(input())
S=input()
print(len(list(itertools.groupby(S))))
import math
N=int(input())
A=list(map(int,input().split()))
print(math.ceil(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]))
N=int(input())
p=[int(input()) for i in range(N)]
print(sum(p)-max(p)//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")
N,L=map(int,input().split())
taste=[L+i for i in range(N)]
print(sum(taste)-min(taste,key=abs))
N,K=map(int,input().split())
H=list(map(int,input().split()))
print(sum(1 for h in H if h>=K))
N,K=map(int,input().split())
H=list(map(int,input().split()))
print(sum(h>=K for h in H))
S=input()
print(sum(S[i]!=S[-i-1] for i in range(len(S)//2)))
ABC153 B - Common Raccoon vs Monster
H,N=map(int,input().split())
A=sum(map(int,input().split()))
print("Yes" if H<=A 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]))
S=input()
T=input()
print(sum(s==t for s,t in zip(S,T)))
A=map(int,input().split())
print("bust" if sum(A)>=22 else "win")
数字和
- 数字和:digit sum
- 数字和 - Wikipedia
string="1234"
print(sum(map(int,string)))
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())))
5.16 zip
- zip():それぞれの iterable から要素を集めた iterator を作り、タプルを返す
Matrix=[[1,2,3],[4,5,6],[7,8,9]]
print(Matrix)
print(list(map(list,zip(*Matrix))))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[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)))
N,M=map(int,input().split())
S,C=[],[]
for m in range(M):
s,c=map(int,input().split())
S.append(s)
C.append(c)
for i in range(10**N):
if len(str(i))==N and all(str(i)[s-1]==str(c) for s,c in zip(S,C)):
print(i)
break
else:
print(-1)
N,M=map(int,input().split())
sc=[tuple(map(int,input().split())) for m in range(M)]
for i in range(10**N):
if len(str(i))==N and all(str(i)[s-1]==str(c) for s,c in sc):
print(i)
break
else:
print(-1)
N,M=map(int,input().split())
sc=[list(map(int,input().split())) for m in range(M)]
for i in range(10**N):
if len(str(i))==N and all(str(i)[s-1]==str(c) for s,c in sc):
print(i)
break
else:
print(-1)
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)
S=input()
print(sum(x!=y for x,y in zip(S,S[::-1]))//2)
ABC148 B - Strings with the Same Length
N=input()
S,T=input().split()
print("".join(s+t for s,t in zip(S,T)))
N=input()
S,T=input().split()
print(*[s+t for s,t in zip(S,T)],sep="")
S=input()
T=input()
print(sum(s==t for s,t in zip(S,T)))
第6章 モジュール観点
6.1 bisect
- bisect:配列二分法アルゴリズム
bisect_left / bisect_right
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)
import bisect
N,X=map(int,input().split())
L=list(map(int,input().split()))
for i in range(N-1):L[i+1]+=L[i]
print(bisect.bisect_left(L,X+1)+1)
6.2 calendar
- calendar:一般的なカレンダーに関する関数群
isleap
うるう年:Leap year
import calendar
print("YES" if calendar.isleap(int(input())) else "NO")
6.3 collections
- collections:コンテナデータ型
Counter
import collections
List=["a","a","a","a","b","c","c"]
c=collections.Counter(List)
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")
import collections
N=int(input())
s=[str(sorted(input())) for i in range(N)]
c=collections.Counter(s)
print(sum((v*(v-1))//2 for v in c.values()))
from collections import Counter
print(Counter([input() for i in range(int(input()))]).most_common()[0][0])
from collections import Counter
S=Counter(input())
print("Yes" if len(S)==2 and len(set(list(S.values())))==1 else "No")
deque
import collections
queue=collections.deque(["a","b","c"])
queue.append("d")
print(queue)
queue.popleft()
print(queue)
deque(['a', 'b', 'c', 'd'])
deque(['b', 'c', 'd'])
6.4 fractions
- fractions:有理数
gcd
ABC118 C - Monsters Battle Royale
import functools
import fractions
N=int(input())
A=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,A))
6.5 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))
6.6 heapq
- heapq:ヒープキューアルゴリズム
heappush / heappop
import heapq
hq=[2,-20,5,0,-1,100,27]
heapq.heappush(hq,-30)
print(hq)
heapq.heappop(hq)
print(hq)
[-30, 2, 5, -20, -1, 100, 27, 0]
[2, -20, 5, 0, -1, 100, 27]
nlargest / nsmallest
import heapq
hq=[2,-20,5,0,-1,100,27]
print(heapq.nlargest(3,hq))
print(heapq.nsmallest(3,hq))
[100, 27, 5]
[-20, -1, 0]
heapreplace
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])
6.7 itertools
- itertools:効率的なループ実行のための iterator 生成関数
accumulate
ABC143 B - TAKOYAKI FESTIVAL 2019
import itertools
N=int(input())
D=list(map(int,input().split()))
print(sum(d*cumulate for d,cumulate in zip(D[1:],itertools.accumulate(D))))
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)]))
combinations_with_replacement
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
groupby
ABC063 C - 一次元リバーシ / 1D Reversi
from itertools import groupby
S=input()
G=groupby(S)
print(len(list(G))-1)
import itertools
N=int(input())
S=input()
print(len(list(itertools.groupby(S))))
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)
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)
import itertools
N=int(input())
P,Q=[tuple(map(int,input().split())) for i in range(2)]
dictionary=sorted(itertools.permutations(P,N))
print(abs(dictionary.index(P)-dictionary.index(Q)))
import itertools
N=int(input())
P,Q=[list(map(int,input().split())) for i in range(2)]
dictionary=sorted(itertools.permutations(P,N))
print(abs(dictionary.index(tuple(P))-dictionary.index(tuple(Q))))
from itertools import permutations
import math
menu=5
times=[int(input()) for i in range(menu)]
orders=list(permutations(times,menu))
minimum=sum(math.ceil(time/10)*10 for time in times)
for order in orders:
total=order[0]
for i in range(1,menu):
total+=math.ceil(order[i]/10)*10
minimum=min(minimum,total)
print(minimum)
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)
6.8 math
- math:数学関数
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))
import math
N,D=map(int,input().split())
print(math.ceil(N/(D*2+1)))
floor
- 床関数(切り捨て):floor
- math.floor()
import math
print(math.floor(5/3))
1
import math
print(math.floor(6/3))
2
log
import math
N,K=map(int,input().split())
print(int(math.log(N,K))+1)
sqrt
- 平方根:square root
- math.sqrt()
import math
print(math.sqrt(4))
2.0
6.9 numpy
- numpy:数値計算
argsort
import numpy
N=int(input())
A=list(map(int,input().split()))
print(*numpy.argsort(A)+1)
array
import numpy as np
from itertools import combinations
N,D=map(int,input().split())
X=[list(map(int,input().split())) for i in range(N)]
count=0
for y,z in combinations(X,2):
count+=(sum(diff**2 for diff in np.array(y)-np.array(z))**.5).is_integer()
print(count)
import numpy as np
from itertools import combinations
N,D=map(int,input().split())
X=[list(map(int,input().split())) for i in range(N)]
print(sum((sum(diff**2 for diff in np.array(y)-np.array(z))**.5).is_integer() for y,z in combinations(X,2)))
norm
import numpy as np
N,D=map(int,input().split())
X=np.array([list(map(int,input().split())) for i in range(N)])
print(sum(1 for i in range(N) for j in range(i+1,N) if np.linalg.norm(X[i]-X[j]).is_integer()))
N=int(input())
xy=[list(map(int,input().split())) for i in range(N)]
print(sum(((xi-xj)**2+(yi-yj)**2)**.5 for xi,yi in xy for xj,yj in xy)/N)
import numpy as np
N=int(input())
xy=np.array([list(map(int,input().split())) for i in range(N)])
print(sum(np.linalg.norm(i-j) for i in xy for j in xy)/N)
6.10 re
- re:正規表現操作(Regular Expression operations)
findall
- re.findall():string 中の pattern による重複しないマッチを文字列のリストとして返す
import re
print(max(map(len,re.findall("[ACGT]*",input()))))
import re
print(*re.findall("[0-9]+",input()))
match
- re.match():string の先頭で0文字以上がこの正規表現とマッチするなら、対応する マッチオブジェクト を返す
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
n=int(input())
f=re.match(r"^((bcabca)*b|(cabcab)*cabca|(abcabc)*abc)$",input())
print(n//2 if f else -1)
import re
print("AC" if re.match("^A[a-z]+C[a-z]+$",input()) else "WA")
search
- re.search():string を走査し、この正規表現がマッチを生じさせる最初の場所を探して、対応する マッチオブジェクト を返す
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")
split
- re.split():string を pattern で分割し、リストを返す
import re
print(max(map(len,re.split("[^ACGT]",input()))))
sub
- re.sub():string を重複しない pattern を置換した文字列を返す
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")
第7章 データ構造観点
7.1 スタック
- スタック:Stack
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))
7.2 キュー
- キュー:Queue
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())
第8章 アルゴリズム観点
ユークリッドの互除法
- 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)
- 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
import fractions
N=int(input())
A=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,A))
from fractions import gcd
A,B,C,D=map(int,input().split())
A-=1
lcm=C*D//gcd(C,D)
print(B-B//C-B//D+B//lcm-(A-A//C-A//D+A//lcm))
最小公倍数(LCM)
- 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
import fractions
N=int(input())
A=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,A))
from fractions import gcd
A,B,C,D=map(int,input().split())
A-=1
lcm=C*D//gcd(C,D)
print(B-B//C-B//D+B//lcm-(A-A//C-A//D+A//lcm))
import fractions
A,B=map(int,input().split())
print(A*B//fractions.gcd(A,B))
a,b,n=[int(input()) for i in range(3)]
while n%a!=0 or n%b!=0:n+=1
print(n)
探索
全探索
N,K=map(int,input().split())
t=[int(input()) for i in range(N)]
flag=True
day=2
for i in range(3,N):
if flag and sum(t[i-3:i])>=K:
day=i
else:
flag=False
print(-1 if day+1==N else day+1)
N,K=map(int,input().split())
t=[int(input()) for i in range(N)]
sleep=[0]*(N-2)
for i in range(N-2):
sleep[i]=sum(t[i:i+3])
day=N
for i in range(N-2):
if sleep[i]<K:
day=min(day,i+3)
print(-1 if day==N else day)
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))
from itertools import permutations
import math
menu=5
times=[int(input()) for i in range(menu)]
orders=list(permutations(times,menu))
minimum=sum(math.ceil(time/10)*10 for time in times)
for order in orders:
total=order[0]
for i in range(1,menu):
total+=math.ceil(order[i]/10)*10
minimum=min(minimum,total)
print(minimum)
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))
ABC143 B - TAKOYAKI FESTIVAL 2019
N=int(input())
d=list(map(int,input().split()))
print(sum(d[x]*d[y] for x in range(N) for y in range(x+1,N)))
- 未分類
ABC002 D - 派閥
ABC018 D - バレンタインデー
ABC031 D - 語呂合わせ
ABC039 D - 画像処理高橋君
ABC075 D - Axis-Parallel Rectangle
深さ優先探索(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"))
import sys
sys.setrecursionlimit(500000)
h,w=map(int,input().split())
l=[list(input()) for i in range(h)]
def dfs(r,c):
if not(0<=c<w and 0<=r<h) or l[r][c]=="#":return
if l[r][c]=="g":
print("Yes")
exit()
l[r][c]="#"
dfs(r+1,c)
dfs(r-1,c)
dfs(r,c+1)
dfs(r,c-1)
for i,y in enumerate(l):
if "s" in y:
dfs(i,y.index("s"))
break
print("No")
- 未解答
幅優先探索(BFS)
- BFS:Breadth First Search
bit全探索
N,M=map(int,input().split())
s=[list(map(int,input().split()))[1:] for m in range(M)]
p=list(map(int,input().split()))
count=0
for i in range(1<<N):
for m in range(M):
switch=0
for j in range(N):
if (i>>j)&1 and j+1 in s[m]:
switch+=1
if switch%2!=p[m]:
break
else:
count+=1
print(count)
N=int(input())
testimony=[[-1]*N for i in range(N)]
count=0
for i in range(N):
A=int(input())
for j in range(A):
x,y=map(int,input().split())
testimony[i][x-1]=y
for i in range(1<<N):
honest=[0]*N
for j in range(N):
if (i>>j)&1:
honest[j]=1
flag=True
for j in range(N):
if honest[j]:
for k in range(N):
if testimony[j][k]==-1:
continue
if testimony[j][k]!=honest[k]:
flag=False
if flag:
count=max(count,honest.count(1))
print(count)
シミュレーション
N,M,A,B=map(int,input().split())
for m in range(M):
if N<=A:
N+=B
c=int(input())
N-=c
if N<0:
print(m+1)
break
else:
print("complete")
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
count=0
for i in range(N):
count+=min(A[i],B[i])
if A[i]<B[i]:
if A[i+1]<B[i]-A[i]:
count+=A[i+1]
A[i+1]=0
else:
count+=B[i]-A[i]
A[i+1]-=B[i]-A[i]
print(count)
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
count=0
for i,b in enumerate(B):
attack=min(b,A[i]+A[i+1])
count+=attack
A[i+1]-=max(0,attack-A[i])
print(count)
A,B=map(int,input().split())
count,outlet=0,1
while(outlet<B):
outlet-=1
outlet+=A
count+=1
print(count)
N,K,Q=map(int,input().split())
A=[int(input()) for i in range(Q)]
point=[0]*N
for a in A:
point[a-1]+=1
for n in range(N):
print("Yes" if point[n]>Q-K else "No")
N,M=map(int,input().split())
ac,wa=0,0
task=[0]*N
for m in range(M):
p,S=input().split()
p=int(p)-1
if task[p]!=-1 and S=="WA":
task[p]+=1
elif task[p]!=-1 and S=="AC":
ac+=1
wa+=task[p]
task[p]=-1
print(ac,wa)
N=int(input())
A,B,C=[list(map(int,input().split())) for i in range(3)]
satisfaction=0
for i in range(N):
satisfaction+=B[A[i]-1]
if i!=0 and A[i]==A[i-1]+1:
satisfaction+=C[A[i-1]-1]
print(satisfaction)
N=int(input())
A,B,C=[list(map(int,input().split())) for i in range(3)]
print(sum(B)+sum(C[A[i]-1] for i in range(N-1) if A[i]==A[i+1]-1))
貪欲法
- 貪欲法(Greedy Algorithm)
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)
s=input()
A,Z=len(s),0
for i in range(len(s)):
if s[i]=="A":
A=min(A,i)
elif s[i]=="Z":
Z=max(Z,i)
print(Z-A+1)
N,K=map(int,input().split())
L=list(map(int,input().split()))
stick=[0]*K
for l in L:
minimum=min(stick)
if l>minimum:
stick.remove(minimum)
stick.append(l)
print(sum(stick))
ABC076 B - Addition and Multiplication
N=int(input())
K=int(input())
display=1
for i in range(N):
display=min(display*2,display+K)
print(display)
ABC=list(map(int,input().split()))
K=int(input())
for k in range(K):
maximum=max(ABC)
ABC.remove(maximum)
ABC.append(maximum*2)
print(sum(ABC))
N=int(input())
total=0
maximum=100
for i in range(N):
p=int(input())
total+=p
maximum=max(maximum,p)
print(total-maximum//2)
import math
orders=[int(input()) for i in range(5)]
maximum,total=0,0
for order in orders:
time=math.ceil(order/10)*10
total+=time
remaine=time-order
maximum=max(maximum,remaine)
print(total-maximum)
N,K=map(int,input().split())
H=list(map(int,input().split()))
count=0
for h in H:
if h>=K:
count+=1
print(count)
N,K=map(int,input().split())
H=list(map(int,input().split()))
print(sum(1 for h in H if h>=K))
N,K=map(int,input().split())
H=list(map(int,input().split()))
print(sum(h>=K for h in H))
動的計画法(DP)
- DP:Dynamic Programming
- フィボナッチ数列
def fib(n):
if n==0:return 0
if n==1:return 1
return fib(n-1)+fib(n-2)
N=int(input())
print(fib(N))
n=int(input())
dp=[0]*(n+1)
dp[0]=0
dp[1]=1
for i in range(2,n+1):dp[i]=dp[i-1]+dp[i-2]
print(dp[n])
n,m=map(int,input().split())
a=set([int(input()) for i in range(m)])
dp=[0]*(n+1)
dp[0]=1
for i in range(1,n+1):
dp[i]=(dp[i-1]+dp[i-2])%(10**9+7)
if i in a:dp[i]=0
print(dp[n])
n,m=map(int,input().split())
a=[int(input()) for i in range(m)]
dp=[0]*(n+1)
dp[0]=1
for i in range(1,n+1):
dp[i]=(dp[i-1]+dp[i-2])%(10**9+7)
if i in a:dp[i]=0
print(dp[n])
N=int(input())
H=list(map(int,input().split()))
h=[0]*N
count=0
for i in range(1,N):
if H[i-1]>=H[i]:
count+=1
else:
count=0
h[i]=count
print(max(h))
N=int(input())
H=list(map(int,input().split()))
h=[0]*N
for i in range(1,N):
if H[i-1]>=H[i]:
h[i]=h[i-1]+1
print(max(h))
n=int(input())
h=list(map(int,input().split()))
dp=[0]*n
dp[0]=0
dp[1]=abs(h[1]-h[0])
for i in range(2,n):dp[i]=min(dp[i-1]+abs(h[i]-h[i-1]),dp[i-2]+abs(h[i]-h[i-2]))
print(dp[n-1])
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 - 経路
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)
グラフ
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
最大フロー
- 未分類
エラトステネスのふるい
- 未解答
ワーシャル?フロイド法
- 未解答
クラスカル法/プリム法
- 未解答
第9章 計算量観点
剰余
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())
A=list(map(int,input().split()))
for i in range(N):
print(A.index(i+1)+1,end=" ")
N=int(input())
A=list(map(int,input().split()))
sort=[0]*N
for i in range(N):
sort[A[i]-1]+=i+1
print(*sort)
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])
N,X=map(int,input().split())
L=list(map(int,input().split()))
for i in range(N-1):L[i+1]+=L[i]
count=1
for i in range(N):
if L[i]<=X:count+=1
print(count)
N,X=map(int,input().split())
L=list(map(int,input().split()))
cumulative,count=0,1
for l in L:
cumulative+=l
if cumulative<=X:count+=1
print(count)
import bisect
N,X=map(int,input().split())
L=list(map(int,input().split()))
for i in range(N-1):L[i+1]+=L[i]
print(bisect.bisect_left(L,X+1)+1)
ABC143 B - TAKOYAKI FESTIVAL 2019
import itertools
N=int(input())
D=list(map(int,input().split()))
print(sum(d*cumulate for d,cumulate in zip(D[1:],itertools.accumulate(D))))
- 未分類
二分探索
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)
A,B,X=map(int,input().split())
minimum=0
maximum=10**9+1
while maximum-minimum>1:
medium=(maximum+minimum)//2
if A*medium+B*len(str(medium))>X:
maximum=medium
else:
minimum=medium
print(minimum)
- 未分類
ABC023 D - 射撃王
ABC026 D - 高橋君ボール1号
ABC034 D - 食塩水
中央値の算出
N=int(input())
X=list(map(int,input().split()))
for i in range(N):
sort=sorted(X[:i]+X[i+1:])
print(sort[N//2-1])
N=int(input())
X=list(map(int,input().split()))
sort=sorted(X)
left=sort[(N//2)-1]
right=sort[N//2]
for x in X:
print(left if left<x else right)
ABC132 C - Divide the Problems
N=int(input())
D=sorted(map(int,input().split()))
maximum=max(D)
medium=0
for threshold in range(1,maximum+1):
count=0
for d in D:
if d<threshold:
count+=1
if count==len(D)//2:
medium+=1
print(medium)
N=int(input())
d=sorted(map(int,input().split()))
print(d[N//2]-d[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))
ABC133 C - Remainder Minimization 2019
L,R=map(int,input().split())
if R-L>=2019:
minimum=0
else:
left,right=L%2019,R%2019
minimum=2018**2
for i in range(left,right+1):
for j in range(i+1,right+1):
minimum=min(minimum,i*j%2019)
print(minimum)
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)
n,y=map(int,input().split())
y//=1000
a=y%5
for i in range(n+1):
if a==i%5:
b=(y-i)//5
c=n-i
if c<=b<=2*c:
print(b-c,2*c-b,i)
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)
N,K=map(int,input().split())
count=0
while(N>0):
N//=K
count+=1
print(count)
import math
N,K=map(int,input().split())
print(int(math.log(N,K))+1)
第10章 数学観点
和差算
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 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)
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、次の項を 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])
n=int(input())
p=list(map(int,input().split()))
count=0
for i in range(n-2):
a,b,c=p[i],p[i+1],p[i+2]
if a<=b<=c or c<=b<=a:count+=1
print(count)
n=int(input())
p=list(map(int,input().split()))
print(len([1 for i in range(n-2) if sorted(p[i:i+3])[1]==p[i+1]]))
n=int(input())
p=list(map(int,input().split()))
print(sum(p[i+1]==sorted(p[i:i+3])[1] for i in range(n-2)))
N=int(input())
p=list(map(int,input().split()))
diff=0
for i in range(N):
if p[i]!=i+1:diff+=1
print("YES" if diff==0 or diff==2 else "NO")
N=int(input())
p=list(map(int,input().split()))
print("YES" if sum(1 for i in range(N) if p[i]!=i+1)<=2 else "NO")
N=int(input())
p=list(map(int,input().split()))
print("YES" if sum(p[i]!=i+1 for i in range(N))<=2 else "NO")
数直線
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")
n=int(input())
b=c=0
for h in map(int,input().split()):
if b<=h:
b=h
c+=1
print(c)
N,X=map(int,input().split())
L=list(map(int,input().split()))
for i in range(N-1):L[i+1]+=L[i]
count=1
for i in range(N):
if L[i]<=X:count+=1
print(count)
N,X=map(int,input().split())
L=list(map(int,input().split()))
cumulative,count=0,1
for l in L:
cumulative+=l
if cumulative<=X:count+=1
print(count)
import bisect
N,X=map(int,input().split())
L=list(map(int,input().split()))
for i in range(N-1):L[i+1]+=L[i]
print(bisect.bisect_left(L,X+1)+1)
K,X=map(int,input().split())
print(*[x for x in range(X-K+1,X+K)])
円と長方形
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))
ABC144 C - Walk on Multiplication Table
N=int(input())
move=10**12
for n in range(1,int(N**.5)+1):
if N%n==0:
move=min(move,N//n+n-2)
print(move)
N=int(input())
X=list(map(int,input().split()))
P=round(sum(X)/N)
print(sum((x-P)**2 for x in X))
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))
W,H,x,y=map(int,input().split())
print(W*H/2,1) if W==2*x and H==2*y else print(W*H/2,0)
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
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(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+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))
a,b,c,x=[int(input()) for i in range(4)]
x//=50
p=min(a,x//10)
ans=0
for i in range(p+1):
y=x-10*i
q=min(b,y//2)
for j in range(q+1):
z=y-2*j
if c>=z:ans+=1
print(ans)
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:小数部)
# 平方値
print(2**.5)
# 整数値
print(int(2**.5))
# 小数値
y=2**.5
x=y-int(y)
print(x)
1.4142135623730951
1
0.41421356237309515
a,b=divmod(5,2)
print(a)
print(b)
2
1
print(int(int(input())**.5)**2)
相加相乗平均
\frac{a+b}{2} ≧ \sqrt{ab}
print(int(input())**2//4)
二乗和と和の二乗
ABC143 B - TAKOYAKI FESTIVAL 2019
N=int(input())
D=list(map(int,input().split()))
print((sum(D)**2-sum(d*d for d in D))//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)
N=int(input())
xy=[list(map(int,input().split())) for i in range(N)]
distance=0
for xi,yi in xy:
for xj,yj in xy:
distance+=((xi-xj)**2+(yi-yj)**2)**.5
print(distance/N)
N,D=map(int,input().split())
X=[list(map(int,input().split())) for i in range(N)]
count=0
for i in range(N):
for j in range(i+1,N):
count+=(sum((y-z)**2 for y,z in zip(X[i],X[j]))**.5).is_integer()
print(count)
import numpy as np
from itertools import combinations
N,D=map(int,input().split())
X=[list(map(int,input().split())) for i in range(N)]
count=0
for y,z in combinations(X,2):
count+=(sum(diff**2 for diff in np.array(y)-np.array(z))**.5).is_integer()
print(count)
import numpy as np
from itertools import combinations
N,D=map(int,input().split())
X=[list(map(int,input().split())) for i in range(N)]
print(sum((sum(diff**2 for diff in np.array(y)-np.array(z))**.5).is_integer() for y,z in combinations(X,2)))
import numpy as np
N,D=map(int,input().split())
X=np.array([list(map(int,input().split())) for i in range(N)])
print(sum(1 for i in range(N) for j in range(i+1,N) if np.linalg.norm(X[i]-X[j]).is_integer()))
マンハッタン距離
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")
行列
行集計
\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))
第11章 カテゴリ観点
桁数
N=int(input())
count=0
for i in range(1,N+1):
if len(str(i))%2==1:count+=1
print(count)
N=int(input())
print(sum(len(str(i))%2==1 for i in range(1,N+1)))
N=int(input())
print(sum(len(str(i))%2 for i in range(1,N+1)))
グリッド
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 i in range(N)]
B=[input() for i in range(M)]
judge=any([line[j:j+M] for line in A[i:i+M]]==B for i in range(N-M+1) for j in range(N-M+1))
print("Yes" if judge 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))
再帰
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))
日時
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))
オセロ
AGC029 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))
ビンゴ
A=[list(map(int,input().split())) for i in range(3)]
N=int(input())
B=[int(input()) for i in range(N)]
a=[[False]*3 for i in range(3)]
for i in range(3):
for j in range(3):
for b in B:
if A[i][j]==b:
a[i][j]=True
bingo=False
for i in range(3):
if a[i][0] and a[i][1] and a[i][2]:
bingo=True
for j in range(3):
if a[0][j] and a[1][j] and a[2][j]:
bingo=True
if a[0][0] and a[1][1] and a[2][2]:
bingo=True
if a[2][0] and a[1][1] and a[2][0]:
bingo=True
print("Yes" if bingo else "No")
ゾロ目
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])
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())
参考
本記事は下記を参考にしました。
ドキュメント
書籍
- 最強最速アルゴリズマー養成講座 プログラミングコンテストTopCoder攻略ガイド Kindle版
- プログラミングコンテストチャレンジブック [第2版] ~問題解決のアルゴリズム活用力とコーディングテクニックを鍛える~ Kindle版
- プログラミングコンテスト攻略のためのアルゴリズムとデータ構造 Kindle版
Python関連ページ
- 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入門 - 演算子
- Python3.xのアスタリスク逆引き
- [Pythonコーディング規約]PEP8を読み解く
- Python の eval と exec
- [python] 文を実行するexec, eval
競技プログラミング関連ページ
- 典型的な DP (動的計画法) のパターンを整理 Part 1 ~ ナップサック DP 編 ~
- Pythonで二分探索する公式ライブラリ
- Pythonで使う競技プログラミング用チートシート
- 実世界で超頻出!二部マッチング (輸送問題、ネットワークフロー問題)の解法を総整理!?
- 線形探索を極める! ? for 文で色んなことができることを知る ?
- 重み付き Union-Find 木とそれが使える問題のまとめ、および、牛ゲーについて
- ビット演算 (bit 演算) の使い方を総特集! ? マスクビットから bit DP まで ?
- AtCoder 版!蟻本 (初級編)
- 【Python】組み合わせ(nCr) 計算の高速化
- AtCoder 版!蟻本 (中級編)
- AtCoder 版!蟻本 (上級編)
- AtCoder に登録したら次にやること ~ これだけ解けば十分闘える!過去問精選 10 問 ~
- AtCoder コンテストについての tips
- AtCoder 版!蟻本 (発展的トピック編)
- ソートを極める! ? なぜソートを学ぶのか ?
- アルゴリズムとは何か!? ~ 文系理系問わず楽しめる精選 6 問 ~
- 二分探索アルゴリズムを一般化 ? めぐる式二分探索法のススメ ?
- 計算量オーダーの求め方を総整理! ? どこから log が出て来るか ?
- Pythonで競プロやるときによく書くコードをまとめてみた
- 特集!知らないと損をする計算量の話
- しゃくとり法 (尺取り法) の解説と、それを用いる問題のまとめ
- 拡張ユークリッドの互除法 ? 一次不定方程式 ax + by = c の解き方 ?
- 貰う DP と配る DP、メモ化再帰、個数制限なしナップサック問題
- 中国剰余定理 (CRT) の解説と、それを用いる問題のまとめ
- 文字列連結の常識、joinは本当に速いのか[Python3]
- 「1000000007 で割ったあまり」の求め方を総特集! ? 逆元から離散対数まで ?
- Python3で競技プログラミングする時に知っておきたいtips(入力編)
- 部分列 DP --- 文字列の部分文字列を重複なく走査する DP の特集
- 最長増加部分列(LIS)の長さを求める
- Pythonで競プロをやる時にそこそこ使う書き方(itertools編)
- フェルマーの小定理の証明と使い方
- atcoderでよく使う手法python版
- 意外と解説がない!動的計画法で得た最適解を「復元」する一般的な方法
- Pythonで競技プログラミング ?基本的なアルゴリズム ?
- 競技プログラミングにおけるXORのTips
- Pythonで競プロに挑む日誌 ~目次ページ~(移設済み)
- 動的計画法超入門! Educational DP Contest の A ~ E 問題の解説と類題集
- Educational DP Contest の F ~ J 問題の解説と類題集
- PythonでAtCoder青になるまで -Pythonで競プロやるときに気をつけること-
- ゲームを解く!Educational DP Contest K, L 問題の解説
- Union-Find構造をPythonで実装した
- UnionFind実装(python3)
- Python de アルゴリズム(bit全探索)
- bit全探索とグレイコード
- 累積和を何も考えずに書けるようにする!
- Pythonでmodintを実装してみた
- Pythonで競技プログラミング -ライブラリ編-
- 再帰関数を学ぶと、どんな世界が広がるか
- 【Python】K番目に大きい組み合わせを取るための3つの方法【heapq 優先度付きキュー】
- 蟻本をPythonで (初級編)
- 「写像12相」を総整理! ? 数え上げ問題の学びの宝庫 ?
- 競技プログラミングで使う有名グラフアルゴリズムまとめ
- 簡単な貪欲法を解いてみた
- AtCoder 最初にやる10題の熟練コードを読む(Python3)
- 競技プログラミングに役立つテクニック 初級編12問
- スタックとキューを極める! ? 考え方と使い所を特集 ?
- AtCoderをPythonで始めるときの環境構築といくつかのTIPS
- 【python】 累積和を取るときのお話
- DFS (深さ優先探索) 超入門! ? グラフ・アルゴリズムの世界への入口 ?【前編】
- DFS (深さ優先探索) 超入門! ? グラフ・アルゴリズムの世界への入口 ?【後編】
- BFS (幅優先探索) 超入門! ? キューを鮮やかに使いこなす ?
- 繰り返し二乗法をpythonで実装してみた
- Pythonで"in list"から"in set"に変えただけで爆速になった件とその理由
- 【競プロ】PythonとPyPyの速度比較
- BitDPについて
- AtCoder Beginner Contest138のD問題を通してDFS(深さ優先探索)を理解した
- [Python] 競技プログラミングで再帰関数を書くときはsys.setrecursionlimitで最大再帰数を上げる
- 幅優先探索(BFS)と深さ優先探索(DFS)
- Python 3 で AtCoder をするあれこれ
- 優先度付きキュー(ヒープ)の使い方
- 尺取り法による部分文字列の探索
- AtCoder 問題カテゴリー分類
- 安全で爆速なRollingHashの話
- AtCoderで深さ優先探索がどうしてもREしてしまった話
- 併合可能優先度付きキューを Python3 で書いちゃおう!
- ユークリッドの互除法による最大公約数の求め方
- 基本的なソートアルゴリズムとPythonによる実装例
- 再帰関数についてpythonで書いた
- 二分探索木におけるノードの削除
- ハッシュテーブル(HashSet, HashMap)の実装
- 循環配列を用いたキューの実装
- スタックによるキューの実装と、キューによるスタックの実装
- AtCoderアルゴリズム実技検定のすゝめ/サンプル問題の解説
- 【入門】 基礎から理解するbit全探索
- Pythonで競技プログラミング(AtCoder)を始めよう
- Pythonで再帰関数の繰り返し回数の上限を設定する
- Pythonでbit全探索
- Pythonで解く競プロテクニック集
- 【Python】深さ優先探索と幅優先探索
- LIS でも大活躍! DP の配列使いまわしテクニックを特集
- Pythonでアルゴリズム(深さ優先探索、dfs)
- いもす法
- 【Python競プロ用メモ】LRUキャッシュはプログラムでのメモ化より早い
- 三分探索を救いたい
- 競技プログラミングにおける作問テクニックを総整理! ?初心者から経験者まで?
- 最短経路問題総特集!!!~BFSから拡張ダイクストラまで~
- 【競プロ】Union-Find木を使って問題を解く!【備忘録】
- 数学オリンピックの問題にプログラミングで挑戦! ~数え上げから幾何問題まで~
- 【図解】線形時間の文字列アルゴリズム「Z algorithm」をイラストとアニメーションでかみ砕く
- Python入門(Python版 APG4b)
- 【Python】AtCoderで使う基礎知識
- AtCoderに登録したら解くべき精選過去問10問の類題をPythonで解く
- 「AtCoder 版!蟻本 (初級編)」をPythonで解く!
- 区間スケジューリング 学習メモ ~by python~
- レッドコーダーが教える、競プロ・AtCoder上達のガイドライン【初級編:競プロを始めよう】
- レッドコーダーが教える、競プロ・AtCoder上達のガイドライン【中級編:目指せ水色コーダー!】
- レッドコーダーが教える、競プロ・AtCoder上達のガイドライン【上級編:目指せレッドコーダー!】
- 【python】nCkを導出する方法(ABC156-D)
- UnionFindをPythonでやるための最低限の実装
- Pythonのスタックとキューには何を使えばいいのか(各データ構造の速度比較)
- 【図解】二分探索はもう間違えない!スリーステップ実装法&記憶に残るアニメーション
- もう数え上げも怖くない ~競プロ数え上げ問題35選~
- 複数のクエリの素因数分解を高速に処理する
- 【競プロ】N枚のカードからM枚取り出す場合の数を、経路を使用して解く【図で解説】
AtCoder関連サービス
AtCoder関連情報
- AtCoderでの勉強の仕方(コンテスト編) - chokudaiのブログ
- AtCoder(競技プログラミング)の色・ランクと実力評価、問題例 - chokudaiのブログ
- 便利リンク集 - AtCoder
- 用語集 - AtCoder Beginner Contest 001
- 利用規約 - AtCoder
- atcoder - Twitter
- AtCoder - Facebook
- AtCoder Live - YouTube