AtCoderの問題を分類しました

はじめに

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

知的財産権
1.本サービスに対して投稿されたプログラムの所有権と著作権は、そのプログラムを作成したユーザに帰属します
2.本サービスを構成する文章、画像、プログラムその他のデータ等についての一切の権利(所有権、知的財産権、肖像権、パブリシティー権等)は、ユーザ自身が作成したものを除き、弊社又は当該権利を有する第三者に帰属しています
3.ユーザ自身が作成した著作物を本サービスを通じて掲載した場合、弊社が宣伝告知等に利用することを許諾するものとします。また、かかる使用に際して、当該ユーザは著作者人格権を行使しないものとします

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

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

最後に

サービスを提供している AtCoder株式会社 と、交流している 競技プログラマ の方々に感謝を致します。

編集履歴

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

  • 初版公開

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

1.1版 編集内容
  • 本記事に「変更管理」項目(本項目)を追加(変更管理をするため)
  • divmod追加(平方根の整数部と小数部の算出、組み込み関数)
  • string.ascii_lowercase追加(文字の集合)
  • 問題追加(ABC-D問題114, 115, 118, 119)
  • 記載修正(ABC063 B - Varied⇒ABC063 A - Restricted)
  • スペル修正(入力処理、Raw⇒Row)
  • スペル修正(利用規約、AtCode⇒AtCoder)
  • スペル修正(約数、Prime⇒Divisor)
  • 「記事の更新方針」項目に「AGC-A問題の追加」を追加(AGCコンテスト対策として)

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

1.2版 編集内容
  • 本章を「変更管理」から「編集履歴」に変更
  • 「実装観点」を「文法観点」「データ型観点」「データ構造観点」に再編し、分類
  • 「入力処理」の入力部分を「入力例」として外出し
  • 「カテゴリ観点」を新規作成
  • 「処理観点」の一部項目を「カテゴリ観点」に移動
  • 正規表現を処理観点に移動
  • サンプルコードの不要な空行を削除
  • 一部の参考サイトを削除(参考にしていないため)
  • レート情報を削除(参考にしていないため)
  • 「複素数」の項目を削除(利用していないため)
  • 記載修正(divmod、enumerate⇒divmod)

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

1.3版 編集内容
  • 章と節に番号を振り分け
  • 「はじめに」と「分類する対象の問題」を修正
  • ABC-A問題を再振り分け

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

1.4版 編集内容
  • ABC-A問題を再振り分け
  • ABC-B問題を再振り分け

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

1.5版 編集内容
  • ABC-B問題を再振り分け
  • 細かい文章の修正

1.6版:2019年08月25日(日)

1.6版 編集内容
  • ABC123~ABC129の問題分類を追加
  • はてなブログへのリンクを削除(はてなブログを削除したため)
  • 問題リンクのスペルミスを修正 (ryunosukeheavenさんコメント指摘)
  • 問題リンクのスペルミスを修正 (hykwさん編集リクエスト)
  • 問題リンクのスペルミスを修正 (tyamagu2さん編集リクエスト)
  • 「ABC024 A - 動物園」の解答例を修正(aboruさんコメント指摘)
  • その他のスペルミスと文言を修正
  • 一部問題の分類を修正

2.0版:2020年03月13日(金)

2.0版 編集内容
  • ABC-A130 ~ ABC-A158 の問題分類を追加
  • ABC-B130 ~ ABC-B158 の問題分類を追加
  • ABC-C130 ~ ABC-C158 の問題分類を追加
  • 「記事の構成」を「構成」に変更
  • 「実行環境」を「バージョン / 言語」に変更
  • 「本記事の対象者」を削除
  • 「コーディング規約」から「コーディング方針」に変更
  • 「コーディング方針」の内容を変更
  • 「記事の更新方針」を「更新方針」に変更
  • 「文法観点」を「入出力観点」「演算観点」「制御フロー観点」に分解
  • 「データ型」から「組み込み型」に変更
  • 「基本処理観点」を「組み込み関数観点」に変更
  • 「応用処理観点」を削除
  • 「実装観点」から「モジュール観点」に変更
  • 「用語」を削除
  • 「参考」を更新
  • 「組み込み型」「組み込み関数」など Python ドキュメントへのリンクを追加
  • 「四捨五入」を削除(情報が誤っていたため)
  • 「bisect」のサンプルコードを修正(コメント内容が誤っていたため)
  • 「小数点切り上げ除算」の一部サンプルコードを削除(演算が誤っていたため)

第1章 入出力観点

1.1 出力

  • print():objects を sep で区切りながらテキストストリーム file に表示し、最後に end を表示する
  • 入力と出力

整数(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)

文字列を出力する

サンプルコード
print("Hello World!")
実行結果
Hello World!

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

サンプルコード
s="Hello World!"
print(s)
実行結果
Hello World!

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

サンプルコード
s="Hello World!"
print(s[0])
print(s[11])
実行結果
H
!

ABC069 B - i18n

解答例
s=input()
print(s[0]+str((len(s)-2))+s[-1])
解答例
a,*b,c=input()
print(a+str(len(b))+c)

ABC041 A - 添字

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

ABC048 A - AtCoder *** Contest

解答例
print("A%sC"%input()[8])
解答例
print("A"+input()[8]+"C")

リスト(list)

1次元リストを出力する

サンプルコード
Lists=[1,2,3,4,5]
print(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))

ABC137 B - One Clue

解答例
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)

ABC085 C - Otoshidama

解答例
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

ABC051 A - Haiku

解答例
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

ABC058 B - ∵∴∵

解答例
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

ABC007 A - 植木算

解答例
print(int(input())-1)

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

入力
Hello world!
サンプルコード
s=input()
print(s)
実行結果
Hello world!

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

入力
1234
サンプルコード
a,b,c,d=input() # 1234を整数(int)型ではなく、文字列(str)型で変数に格納する
print(a,b,c,d)
実行結果
1 2 3 4
入力
abcd
サンプルコード
a,b,c,d=input()
print(a,b,c,d)
実行結果
a b c d

ABC020 A - クイズ

解答例
print("ABC" if input()=="1" else "chokudai")

ABC070 A - Palindromic Number

解答例
a,b,c=input()
print("Yes" if a==c else "No")
解答例
n=input()
print("Yes" if n[0]==n[2] else "No")

ABC079 A - Good Integer

解答例
a,b,c,d=input()
print("Yes" if a==b==c or b==c==d else "No")
解答例
n=input()
print("Yes" if n[0]==n[1]==n[2] or n[1]==n[2]==n[3] else "No")

ABC131 A - Security

解答例
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

ABC012 A - スワップ

解答例
a,b=map(int,input().split())
print(b,a)

ABC149 A - Strings

解答例
S,T=input().split()
print(T+S)

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

入力
Hello world!
サンプルコード
a,b=input().split()
print(a)
print(b)
実行結果
Hello
world!

ABC012 A - スワップ

解答例
a,b=input().split()
print(b,a)

ABC051 A - Haiku

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

ABC056 A - HonestOrDishonest

解答例
a,_,b=input()
print("DH"[a==b])

ABC079 A - Good Integer

解答例
a,b,c,d=input()
print("Yes" if a==b==c or b==c==d else "No")

ABC110 A - Maximize the Formula

解答例
A,B,C=sorted(map(int,input().split()))
print(10*C+B+A)

ABC116 A - Right Triangle

解答例
a,b,c=map(int,input().split())
print(a*b//2)

リストに整数を格納する

入力
1 2 3 4 5
サンプルコード
List=list(map(int,input().split()))
print(List)
実行結果
[1, 2, 3, 4, 5]
入力
1 2 3 4 5
サンプルコード
List=[int(i) for i in input().split()]
print(List)
実行結果
[1, 2, 3, 4, 5]

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

入力
Hello world !
サンプルコード
List=list(input().split())
print(List)
実行結果
['Hello', 'world', '!']
入力
Hello world !
サンプルコード
List=[i for i in input().split()]
print(List)
実行結果
['Hello', 'world', '!']

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

ABC069 B - i18n

解答例
a,*b,c=input()
print(a+str(len(b))+c)

ABC051 A - Haiku

解答例
print(*input().split(","))

ABC103 A - Task Scheduling Problem

解答例
*a,=map(int,input().split())
print(max(a)-min(a))

複数行 / 1列

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

入力
1
2
サンプルコード
a=int(input())
b=int(input())
print(a,b)
実行結果
1 2
入力
1
2
サンプルコード
a,b=[int(input()) for i in range(2)]
print(a,b)
実行結果
1 2

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

解答例
n,k,x,y=(int(input()) for i in [0]*4)
print(n*x-(x-y)*max(n-k,0))

ABC087 A - Buying Sweets

解答例
x,a,b=[int(input()) for _ in range(3)]
print((x-a)%b)

ABC092 A - Traveling Budget

解答例
a,b,c,d=[int(input()) for _ in range(4)]
print(min(a,b)+min(c,d))

リストに格納する

入力
1
2
3
4
5
サンプルコード
List=[int(input()) for i in range(5)]
print(List)
実行結果
[1, 2, 3, 4, 5]

ABC085 B - Kagami Mochi

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

ABC091 B - Two Colors Card Game

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

ABC115 B - Christmas Eve Eve

解答例
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]

ABC031 B - 運動管理

解答例
l,w=map(int,input().split())
n=int(input())
for i in range(n):
    a=int(input())
    print(l-a if l>a else "0" if w>=a else "-1")

ABC112 B - Time Limit Exceeded

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

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

入力
5
a
b
c
d
e
サンプルコード
Row=int(input()) 
List=[input() for i in range(Row)]
print(List)
実行結果
['a', 'b', 'c', 'd', 'e']

複数行 / 複数列

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

入力
3
0 a
1 b
2 c
サンプルコード
Row=int(input())
Number=[]
Alphabet=[]
for i in range(Row):
    n,a=input().split()
    Number.append(int(n))
    Alphabet.append(a)
print(Number)
print(Alphabet)
実行結果
[0, 1, 2]
['a', 'b', 'c']

ABC033 B - 町の合併

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

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

入力
3
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
サンプルコード
Row=int(input())
List=[list(map(int,input().split())) for i in range(Row)]
print(List)
実行結果
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
入力
3
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
サンプルコード
Row=int(input())
List=[[int(j) for j in input().split()] for i in range(Row)]
print(List)
実行結果
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
入力
3
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
サンプルコード
Row=int(input())
List=[]
for i in range(Row):
    List.append(list(map(int,input().split())))
print(List)
実行結果
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

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

入力
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
サンプルコード
List=[list(map(int,input().split())) for i in range(3)]
print(List)
実行結果
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

1次元リストに格納する

入力
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
サンプルコード
List=[]
for i in range(3):
    List+=list(map(int,input().split()))
print(List)
実行結果
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

変数に格納する

入力
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
サンプルコード
a=" ".join([input() for i in [0]*3])
print(a)
実行結果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

ABC037 B - 編集

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

ABC094 B - Toll Gates

解答例
n,m,x=map(int,input().split())
s=sum(int(i)<x for i in input().split())
print(min(s,m-s))

ABC118 B - Foods Loved by Everyone

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

ABC121 B - Can you solve this?

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

第2章 演算観点

2.1 算術演算

演算子 記述例 意味
+ a+b 加算
- a-b 減算
* a*b 乗算
** a**b べき乗 / べき根
/ a/b 除算
// a//b 小数点切り捨て除算
% a%b 剰余

加算

サンプルコード
print(1+2)
実行結果
3

ABC063 A - Restricted

解答例
a,b=map(int,input().split())
print(a+b if a+b<10 else "error")

ABC110 A - Maximize the Formula

解答例
A,B,C=sorted(map(int,input().split()))
print(10*C+B+A)
解答例
l=list(map(int,input().split()))
print(sum(l)+max(l)*9)

減算

サンプルコード
print(2-1)
実行結果
1

ABC013 B - 錠

解答例
x=abs(int(input())-int(input()))
print(min(x,10-x))

ABC073 B - Theater

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

ABC001 A - 積雪深差

解答例
print(int(input())-int(input()))

ABC007 A - 植木算

解答例
print(int(input())-1)

ABC008 A - アルバム

解答例
s,t=map(int,input().split())
print(t-s+1)

ABC058 A - ι⊥l

解答例
a,b,c=map(int,input().split())
print("YES" if b-a==c-b else "NO")

ABC072 A - Sandglass2

解答例
x,t=map(int,input().split())
print("0" if x-t<0 else x-t)

ABC074 A - Bichrome Cells

解答例
print(int(input())**2-int(input()))

ABC076 A - Rating Goal

解答例
print(-int(input())+2*int(input()))

ABC084 A - New Year

解答例
print(48-int(input()))

ABC103 A - Task Scheduling Problem

解答例
A=list(map(int,input().split()))
print(max(A)-min(A))
解答例
a,b,c=sorted(map(int,input().split()))
print(c-a)

ABC106 A - Garden

解答例
a,b=map(int,input().split())
print(a*b-(a+b-1))

ABC107 A - Train

解答例
n,i=map(int,input().split())
print(n-i+1)

ABC123 A - Five Antennas

解答例
a,b,c,d,e,k=[int(input()) for i in range(6)]
print("Yay!" if abs(a-e)<=k else ":(")

ABC136 A - Transfer

解答例
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

ABC004 A - 流行

解答例
print(int(input())*2)

ABC017 A - プロコン

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

ABC028 A - テスト評価

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

ABC031 A - ゲーム

解答例
a,d=map(int,input().split())
print(a*d+max(a,d))
解答例
a,d=map(int,input().split())
print(max(a,d)*(min(a,d)+1))

ABC052 A - Two Rectangles

解答例
a,b,c,d=map(int,input().split())
print(max(a*b,c*d))

ABC069 A - K-City

解答例
n,m=map(int,input().split())
print((n-1)*(m-1))

ABC076 A - Rating Goal

解答例
print(-int(input())+2*int(input()))

ABC106 A - Garden

解答例
a,b=map(int,input().split())
print(a*b-(a+b-1))

ABC121 A - White Cells

サンプルコード
H,W=map(int,input().split())
h,w=map(int,input().split())
print((H-h)*(W-w))

ABC150 A - 500 Yen Coins

サンプルコード
K,X=map(int,input().split())
print("Yes" if 500*K>=X else "No")

階乗

サンプルコード
import math
print(math.factorial(5))
実行結果
120

ABC055 B - Training Camp

解答例
import math
print(math.factorial(int(input()))%(10**9+7))
解答例
ans=1
n=int(input())
for i in range(1,n+1):
    ans*=i
    ans=ans%(10**9+7)
print(ans)

べき乗

サンプルコード
print(2**3)
実行結果
8
サンプルコード
print(10**9+7)
実行結果
1000000007

ABC068 B - Break Number

解答例
print(2**(len(bin(int(input())))-3))
解答例
n=int(input())
ans=1
for i in range(7):
    if 2**i<=n:ans=2**i
print(ans)

ARC036 A - 数え上げ

解答例
print(10**int(input())+7)

ABC097 B - Exponential

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

ABC074 A - Bichrome Cells

解答例
print(int(input())**2-int(input()))

ABC134 A - Dodecagon

解答例
print(3*int(input())**2)

ABC140 A - Password

解答例
print(int(input())**3)

ABC145 A - Circle

解答例
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

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

解答例
print(int(int(input())**.25))

ABC077 B - Around Square

解答例
print(int(int(input())**.5)**2)

ABC086 B - 1 21

解答例
print("No" if int(input().replace(" ",""))**.5%1 else "Yes")
解答例
c=int(input().replace(" ",""))
print("Yes" if c==int(c**.5)**2 else "No")

除算

サンプルコード
print(6/3)
実行結果
2.0

ABC138 C - Alchemist

解答例
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

ABC078 B - ISU

解答例
x,y,z=map(int,input().split())
print((x-z)//(y+z))

ABC095 B - Bitter Alchemy

解答例
n,x=map(int,input().split())
l=[int(input()) for _ in range(n)]
print(n+((x-sum(l))//min(l)))

ABC158 B - Count Balls

解答例
N,A,B=map(int,input().split())
div=N//(A+B)
mod=N%(A+B)
print(div*A+min(mod,A))

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

解答例
x,y=map(int,input().split())
print(y//x)

ABC030 A - 勝率計算

解答例
a,b,c,d=map(int,input().split())
T,A=b/a,d/c
print("TAKAHASHI" if T>A else "AOKI" if T<A else "DRAW")

ABC055 A - Restaurant

解答例
n=int(input())
print(n*800-n//15*200)

ABC089 A - Grouping 2

解答例
print(int(input())//3)

ABC108 A - Pair

解答例
print(int(input())**2//4)
解答例
k=int(input())
print((k//2)*((k+1)//2))

ABC113 A - Discount Fare

解答例
x,y=map(int,input().split())
print(x+y//2)

ABC116 A - Right Triangle

解答例
a,b,c=map(int,input().split())
print(a*b//2)

ABC117 A - Entrance Examination

解答例
print(eval(input().replace(" ","/")))

ABC128 A - Apple Pie

解答例
a,p=map(int,input().split())
print((3*a+p)//2)

ABC142 A - Odds of Oddness

解答例
N=int(input())
print("0.5" if N%2==0 else ((N//2)+1)/N)
解答例
N=int(input())
print((N-N//2)/N)

ABC153 A - Serval vs Monster

解答例
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)

ABC015 B - 高橋くんの集計

解答例
import math
N=int(input())
A=list(map(int,input().split()))
print(math.ceil(sum(A)/(N-A.count(0))))

ABC123 B - Five Dishes

解答例
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)

ABC134 B - Golden Apple

解答例
import math
N,D=map(int,input().split())
print(math.ceil(N/(D*2+1)))

ABC139 B - Power Socket

解答例
import math
A,B=map(int,input().split())
print(1+math.ceil((B-A)/(A-1)))

ABC036 A - お茶

解答例
import math
A,B=map(int,input().split())
print(math.ceil(B/A))

ABC082 A - Round Up the Mean

解答例
import math
a,b=map(int,input().split())
print(math.ceil((a+b)/2))

ABC157 A - Duplex Printing

解答例
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

ABC099 C - Strange Bank

解答例
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)))

ABC034 B - ペア

解答例
n=int(input())
print(n+1 if n%2 else n-1)

ABC041 B - 直方体

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

ABC060 B - Choose Integers

解答例
a,b,c=map(int,input().split())
print("YES" if any((a*i)%b==c for i in range(1,b+1)) else "NO")

ABC146 B - ROT N

解答例
N=int(input())
S=input()
print("".join(chr(65+(ord(s)-65+N)%26) for s in S))

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

解答例
N=int(input())
print(N//10*100+min(100,N%10*15)

ABC009 A - 引越し作業

解答例
n=int(input())
print(n//2+n%2)

ABC011 A - 来月は何月?

解答例
print(int(input())%12+1)

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

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

ABC016 A - 12月6日

解答例
m,d=map(int,input().split())
print("NO" if m%d else "YES")

ARC035 A - テレビ

解答例
w,h=map(int,input().split())
print("16:9" if w*h%144==0 else "4:3")

ABC054 A - One Card Poker

解答例
a,b=map(int,input().split())
print("Draw" if a==b else "Bob" if (a+13)%15<(b+13)%15 else "Alice")

ABC057 A - Remaining Time

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

ABC064 A - RGB Cards

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

ABC067 A - Sharing Cookies

解答例
a,b=map(int,input().split())
print("Impossible" if a*b*(a+b)%3 else "Possible")

ABC081 A - Placing Marbles

解答例
print(int(input())%9)

ABC086 A - Product

解答例
a,b=map(int,input().split())
print("Odd" if a*b%2 else "Even")

ABC087 A - Buying Sweets

解答例
x,a,b=[int(input()) for _ in range(3)]
print((x-a)%b)

ABC088 A - Infinite Coins

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

ABC102 A - Multiple of 2 and N

解答例
n=int(input())
print(n+n%2*n)
解答例
N=int(input())
print(N if N%2==0 else N*2)

ABC105 A - AtCoder Crackers

解答例
print((eval(input().replace(" ","%"))>0)+0)
解答例
N,K=map(int,input().split())
print(0 if N%K==0 else 1)

ABC118 A - B +/- A

解答例
a,b=map(int,input().split())
print(b-a if b%a>0 else a+b)

ABC135 A - Harmony

解答例
A,B=map(int,input().split())
print((A+B)//2 if (A+B)%2==0 else "IMPOSSIBLE")

ABC153 A - Serval vs Monster

解答例
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)

ABC157 A - Duplex Printing

解答例
N=int(input())
print(N//2+N%2)
解答例
N=int(input())
print((N+1)//2)

ABC158 B - Count Balls

解答例
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

ABC006 B - トリボナッチ数列

解答例
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)

ABC079 B - Lucas Number

解答例
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 が偽であれば真

ARC002 A - うるう年

解答例
Y=int(input())
print("YES" if Y%4==0 and Y%100!=0 or Y%400==0 else "NO")

ABC038 B - ディスプレイ

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

ABC155 B - Papers, Please

解答例
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")

ABC094 A - Cats and Dogs

解答例
a,b,x=map(int,input().split())
print("YES" if a<=x and x<=a+b else "NO")

ABC097 A - Colorful Transceivers

解答例
a,b,c,d=map(int,input().split())
print("Yes" if abs(c-a)<=d or abs(b-a)<=d and abs(c-b)<=d else "No")

ABC100 A - Happy Birthday!

解答例
a,b=map(int,input().split())
print("Yay!" if a<9 and b<9 else ":(")

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 以下

ABC082 B - Two Anagrams

解答例
s=sorted(input())
t=sorted(input())[::-1]
print("Yes" if s<t else "No")

ABC119 A - Still TBD

解答例
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

ABC130 C - Rectangle Cutting

解答例
W,H,x,y=map(int,input().split())
print(W*H/2,int(W==2*x and H==2*y))

ABC029 B - カキ

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

ABC022 A - Best Body

解答例
n,s,t=map(int,input().split())
w=c=0
for i in range(n):
    w+=int(input())
    c+=s<=w<=t
print(c)

ABC024 A - 動物園

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

ABC096 A - Day of Takahashi

解答例
a,b=map(int,input().split())
print(a-(a>b))

ABC105 A - AtCoder Crackers

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

ABC130 A - Rounding

解答例
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

ABC155 B - Papers, Please

解答例
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

ABC008 A - アルバム

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

ABC069 A - K-City

解答例
a,b=map(int,input().split())
print(~-a*~-b)

ABC106 A - Garden

解答例
a,b=map(int,input().split())
print(~-a*~-b)

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

ABC104 A - Rated for Me

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

ABC108 A - Pair

解答例
print(int(input())**2>>2)

第3章 制御フロー観点

3.1 条件式

if/else文

ARC002 A - うるう年

解答例
Y=int(input())
print("YES" if Y%4==0 and Y%100!=0 or Y%400==0 else "NO")

ABC130 C - Rectangle Cutting

解答例
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))

ABC016 B - A±B Problem

解答例
a,b,c=map(int,input().split())
print("?" if a+b==c and a-b==c else "+" if a+b==c else "-" if a-b==c else "!")

ABC031 B - 運動管理

解答例
l,w=map(int,input().split())
n=int(input())
for i in range(n):
    a=int(input())
    print(l-a if l>a else "0" if w>=a else "-1")

ABC059 B - Comparison

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

ABC149 B - Greedy Takahashi

解答例
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)

ABC020 A - クイズ

解答例
print("ABC" if input()=="1" else "chokudai")

ABC028 A - テスト評価

解答例
n=int(input())
print("Bad" if n<60 else "Good" if n<90 else "Great" if n<100 else "Perfect")

ABC030 A - 勝率計算

解答例
a,b,c,d=map(int,input().split())
T,A=b/a,d/c
print("TAKAHASHI" if T>A else "AOKI" if T<A else "DRAW")

ABC034 A - テスト

解答例
x,y=map(int,input().split())
print("Better" if x<y else "Worse")

ABC053 A - ABC/ARC

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

ABC056 A - HonestOrDishonest

解答例
a,b=input().split()
print("H" if a==b else "D")

ABC065 A - Expired?

解答例
x,a,b=map(int,input().split())
print("dangerous" if x<b-a else "safe" if a<b else "delicious")

ABC072 A - Sandglass2

解答例
x,t=map(int,input().split())
print("0" if x-t<0 else x-t)

ABC075 A - One out of Three

解答例
a,b,c=map(int,input().split())
print(a if b==c else b if a==c else c)

ABC078 A - HEX

解答例
x,y=input().split()
print("<" if x<y else "=" if x==y else ">")

ABC083 A - Libra

解答例
a,b,c,d=map(int,input().split())
print("Left" if a+b>c+d else "Balanced" if a+b==c+d else "Right")

ABC091 A - Two Coins

解答例
a,b,c=map(int,input().split())
print("Yes" if a+b>=c else "No")

ABC096 A - Day of Takahashi

解答例
a,b=map(int,input().split())
print(a-1 if a>b else a)

ABC099 A - ABD

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

ABC104 A - Rated for Me

解答例
r=int(input())
print("ABC" if r<1200 else "ARC" if r<2800 else "AGC")

ABC112 A - Programming Education

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

ABC122 A - Double Helix

解答例
b=input()
print("A" if b=="T" else "T" if b=="A" else "G" if b=="C" else "C")

ABC130 A - Rounding

解答例
X,A=map(int,input().split())
print("0" if X<A else "10")

ABC138 A - Red or Not

解答例
a=int(input())
s=input()
print(s if a>=3200 else "red")

ABC141 A - Weather Prediction

解答例
S=input()
print("Sunny" if S=="Rainy" else "Cloudy" if S=="Sunny" else "Rainy")

ABC150 A - 500 Yen Coins

サンプルコード
K,X=map(int,input().split())
print("Yes" if 500*K>=X else "No")

ABC152 A - AC or WA

解答例
N,M=input().split()
print("Yes" if N==M else "No")

ABC154 A - Remaining Balls

解答例
S,T=input().split()
A,B=map(int,input().split())
U=input()
print(A-1,B) if S==U else print(A,B-1)

ABC156 A - Beginner

解答例
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))

ABC157 A - Duplex Printing

解答例
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

ABC033 C - 数式の書き換え

解答例
S=map(str,input().split("+"))
ans=0
for s in S:
    if "0" not in s:ans+=1
print(ans)

ABC029 B - カキ

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

ABC089 B - Hina Arare

解答例
input()
l=map(str,input().split())
print("Three" if len(set(l))==3 else "Four")
解答例
input()
print("Four" if "Y" in input() else "Three")

ABC103 B - String Rotation

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

ABC122 B - ATCoder

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

ABC006 A - 世界のFizzBuzz

解答例
print("YES" if input() in "369" else "NO")

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

解答例
print("vowel" if input() in "aiueo" else "consonant")

ABC073 A - September 9

解答例
print("Yes" if "9" in input() else "No")

ABC109 A - ABC333

解答例
print("No" if "2" in input() else "Yes")

ABC114 A - 753

解答例
print("YES" if input() in "753" else "NO")

複数条件式

ABC061 A - Between Two Integers

解答例
a,b,c=map(int,input().split())
print("Yes" if a<=c<=b else "No")

ABC079 A - Good Integer

解答例
a,b,c,d=input()
print("Yes" if a==b==c or b==c==d else "No")

ABC079 A - Good Integer

解答例
a,b,c,d=input()
print("Yes" if a==b==c or b==c==d else "No")

ABC094 A - Cats and Dogs

解答例
a,b,x=map(int,input().split())
print("YES" if a<=x<=a+b else "NO")
解答例
a,b,x=map(int,input().split())
print("YES" if 0<=x-a<=b else "NO")

ABC131 A - Security

解答例
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")

ABC144 A - 9x9

解答例
A,B=map(int,input().split())
print(A*B if 1<=A<=9 and 1<=B<=9 else "-1")

3.2 繰り返し文

for文

ARC010 A - 名刺交換

解答例
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")

ARC036 A - ぐっすり

解答例
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)

ABC085 C - Otoshidama

解答例
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)

ABC136 C - Build Stairs

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)

ABC157 C - Guess The Number

解答例
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)

ABC158 C - Tax Increase

解答例
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)

ABC144 B - 81

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)

ABC149 C - Next Prime

解答例
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())

ABC065 B - Trained?

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

ABC066 B - ss

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

ABC081 B - Shift only

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

ABC116 B - Collatz Problem

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

ABC156 B - Digits

解答例
N,K=map(int,input().split())
count=0
while(N>0):
    N//=K
    count+=1
print(count)

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

解答例
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

ABC119 B - Digital Gifts

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

ARC018 A - BMI

解答例
H,B=map(float,input().split())
print(H**2*B/1e4)

整数判定

  • float.is_integer():浮動小数点数が整数値ならTrueを、そうでなければFalseを返す
サンプルコード
x=1.0
print(x.is_integer())
実行結果
True
サンプルコード
x=1.1
print(x.is_integer())
実行結果
False

ABC144 B - 81

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

文字列の結合

サンプルコード
print("foo"+"bar")
実行結果
foobar

ABC010 A - ハンドルネーム

解答例
print(input()+"pp")

ABC029 A - 複数形

解答例
print(input()+"s")

ABC068 A - ABCxxx

解答例
print("ABC"+input())

ABC090 A - Diagonal String

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

ABC149 A - Strings

解答例
S,T=input().split()
print(T+S)

文字列の繰り返し

ABC020 B - 足し算

解答例
a,b=input().split()
print(2*int(a+b))

ABC152 B - Comparing Strings

解答例
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)))

ABC154 B - I miss you...

解答例
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

ABC069 B - i18n

解答例
s=input()
print(s[0]+str((len(s)-2))+s[-1])

ABC025 A - 25個の文字列

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

ABC038 A - お茶

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

ABC048 A - AtCoder *** Contest

解答例
print("A%sC"%input()[8])
解答例
print("A"+input()[8]+"C")

ABC059 A - Three-letter acronym

解答例
a,b,c=input().split()
print((a[0]+b[0]+c[0]).upper())

ABC060 A - Shiritori

解答例
a,b,c=input().split()
print("YES" if a[-1]==b[0] and b[-1]==c[0] else "NO")

ABC062 A - Grouping

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

ABC070 A - Palindromic Number

解答例
n=input()
print("Yes" if n[0]==n[2] else "No")

ABC079 A - Good Integer

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

ABC090 A - Diagonal String

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

ABC131 A - Security

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")

ABC139 A - Tenki

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]]))

ABC012 A - スワップ

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

ABC070 A - Palindromic Number

解答例
n=input()
print("Yes" if n==n[::-1] else "No")

ABC077 A - Rotation

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

文字列の比較

ABC082 B - Two Anagrams

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

ABC147 B - Palindrome-philia

解答例
S=input()
print(sum(S[i]!=S[-i-1] for i in range(len(S)//2)))

ABC150 B - Count ABC

解答例
N=int(input())
S=input()
print(sum(S[i:i+3]=="ABC" for i in range(N-2)))

ABC119 A - Still TBD

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

ABC139 A - Tenki

解答例
S=input()
T=input()
print(sum(s==t for s,t in zip(S,T)))

文字列の置換

サンプルコード
String="aabbccbbaabbaacc"
print(String.replace("bb","xx"))
実行結果
aaxxccxxaaxxaacc

ARC019 A - お買い物クライシス

解答例
S=input()
for b,a in zip("ODIZSB","001258"):
    S=S.replace(b,a)
print(S)
解答例
S=input()
b="ODIZSB"
a="001258"
for i in range(6):
    S=S.replace(b[i],a[i])
print(S)
解答例
print(input().replace("O","0").replace("D","0").replace("I","1").replace("Z","2").replace("S","5").replace("B","8"))

ARC045 A - スペース高橋君

解答例
print(input().replace("Left","<").replace("Right",">").replace("AtCoder","A"))

ABC017 B - choku語

解答例
print("YES" if input().replace("ch","").replace("o","").replace("k","").replace("u","")=="" else "NO")

ABC020 B - 足し算

解答例
print(2*int(input().replace(" ","")))

ABC041 B - 直方体

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

ABC104 B - AcCepted

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

ABC017 A - プロコン

解答例
print(sum(eval(input().replace(" ","*")) for i in range(3))//10)

ABC027 A - 長方形

解答例
print(eval(input().replace(" ","^")))

ABC085 A - Already 2018

解答例
print("2018"+input()[4:])

ABC107 A - Train

解答例
print(eval(input().replace(" ","-"))+1)

ABC109 A - ABC333

解答例
print("No" if eval(input().replace(" ","*"))%2==0 else "Yes")

ABC111 A - AtCoder Beginner Contest 999

解答例
print(input().replace("1","x").replace("9","1").replace("x","9"))

ABC117 A - Entrance Examination

解答例
print(eval(input().replace(" ","/")))

文字列のコピー

ABC018 B - 文字列の反転

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

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

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

ABC066 B - ss

解答例
s=input()[:-1]
while s[:len(s)//2]!=s[len(s)//2:]:s=s[:-1]
print(len(s))

文字列の判定

サンプルコード
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

ABC071 B - Not Found

解答例
print(min(set(map(chr,range(97,123)))-set(input())or["None"]))
解答例
letters="abcdefghijklmnopqrstuvwxyz"
ans=sorted(set(letters)^set(input()))
print("None" if len(ans)==0 else ans[0])

ABC090 B - Palindromic Numbers

解答例
a,b=map(int,input().split())
print(sum(i==i[::-1] for i in map(str,range(a,b+1))))
解答例
a,b=map(int,input().split())
print(len([i for i in map(str,range(a,b+1)) if i==i[::-1]]))

ABC078 A - HEX

解答例
x,y=input().split()
print("<" if x<y else "=" if x==y else ">")
  • str.isdecimal():全ての文字が十進数字なら真、そうでなければ偽(半角・全角のアラビア数字が真)
  • str.isdigit():全ての文字が数字なら真、そうでなければ偽(半角・全角のアラビア数字、特殊数字が真)
  • str.isnumeric():全ての文字が数を表す文字なら真、そうでなければ偽(半角・全角のアラビア数字、特殊数字、漢数字が真)
  • str.isalpha():全ての文字が英字なら真、そうでなければ偽(便宜上「英字」と書いているが、平仮名やカタカナ、漢字なども真)
  • str.isalnum():全ての文字が英数字なら真、そうでなければ偽(各文字が上のメソッドで真となれば真)

isdecimal

サンプルコード
s="1234567890"
print(s.isdecimal())
実行結果
True

ABC084 B - Postal Code

解答例
a,b=map(int,input().split())
s=input()
if 1<=a<=5 and 1<=b<=5:
    if s[a]=="-":
        if s[0:a].isdecimal() and s[a+1:a+b+1].isdecimal():
            print("Yes")
            exit()
print("No")

isdigit

サンプルコード
s="\u00B2" # 2乗
print(s.isdigit())
実行結果
True

ARC052 A - 何期生?

解答例
print("".join(i for i in input() if i.isdigit()))

isnumeric

サンプルコード
s="一二三四五六七八九〇壱億参阡萬"
print(s.isnumeric())
実行結果
True

isalpha

サンプルコード
s="abcあいうアイウ漢字"
print(s.isalpha())
実行結果
True

isalnum

サンプルコード
s="abc100"
print(s.isalnum())
実行結果
True

文字列の検索

ABC039 C - ピアニスト高橋君

解答例
S=input()[0:12]
key="WBWBWWBWBWBW"*2
ans=["Do","","Re","","Mi","Fa","","So","","La","","Si"]
print(ans[(key.find(S))])

ABC053 B - A to Z String

解答例
s=input()
print(s.rfind("Z")-s.find("A")+1)

大文字小文字変換

  • str.upper():すべての文字列を大文字に変換する
  • str.lower():すべての文字列を小文字に変換する
  • str.capitalize():文字列の先頭文字を大文字に変換する
  • str.title():各単語の先頭文字を大文字に変換する

upper

サンプルコード
Text="this is a pen."
print(Text.upper())
実行結果
THIS IS A PEN.

ABC011 B - 名前の確認

解答例
s=input()
print(s[0].upper()+s[1:].lower())

ABC059 A - Three-letter acronym

解答例
for a in input().upper().split():print(a[0],end="")
解答例
a,b,c=input().split()
print((a[0]+b[0]+c[0]).upper())

lower

サンプルコード
Text="THIS IS A PEN."
print(Text.lower())
実行結果
this is a pen.

ABC011 B - 名前の確認

解答例
s=input()
print(s[0].upper()+s[1:].lower())

capitalize

サンプルコード
Text="this is a pen."
print(Text.capitalize())
実行結果
This is a pen.

ABC011 B - 名前の確認

解答例
print("abcd".capitalize())

title

サンプルコード
Text="this is a pen."
print(Text.title())
実行結果
This Is A Pen.

大文字小文字判定

ABC104 B - AcCepted

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

文字列の変換

ARC019 A - お買い物クライシス

解答例
print(input().translate(str.maketrans("ODIZSB","001258")))

4.4 list

要素の追加

サンプルコード
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=["a","b","c"]
List.extend(["d","e"])
print(List)
実行結果
['a', 'b', 'c', 'd', 'e']

要素の挿入

サンプルコード
List=["a","b","c"]
List.insert(1,"z")
print(List)
実行結果
['a', 'z', 'b', 'c']
サンプルコード
List=["a","b","c"]
List.insert(1,["x","y"])
print(List)
実行結果
['a', ['x', 'y'], 'b', 'c']

ARC049 A - "強調"

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

要素の探索

サンプルコード
List=["a","b","c","d","e","f"]
print(List.index("c"))
実行結果
2
サンプルコード
List=["a","b","c","d","c","c"]
print(List.index("c"))
実行結果
2

ARC003 A - GPA計算

解答例
print((1/int(input()))*sum("FDCBA".index(r) for r in input()))
解答例
N=int(input())
print(sum(map(int,input().translate(str.maketrans("FDCBA","01234"))))/N)

ARC053 B - A to Z String

解答例
s=input()
print(len(s)-s[::-1].index("Z")-s.index("A"))

ABC033 B - 町の合併

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

ABC113 B - Palace

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

ABC013 A - A

解答例
print("0ABCDE".index(input()))
解答例
print(["A","B","C","D","E"].index(input())+1)

ABC018 A - 豆まき

解答例
X=[int(input()) for i in range(3)]
for x in X:print(3-sorted(X).index(x))
解答例
l=[int(input()) for _ in range(3)]
s=sorted(l)[::-1]
for i in l:
    print(s.index(i)+1)

ABC141 A - Weather Prediction

解答例
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=["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=["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']

要素の削除

サンプルコード
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=["a","b","b","c","c","c"]
print(List.count("c"))
実行結果
3
サンプルコード
List=["a","b","b","c","c","c"]
print(List.count("d"))
実行結果
0

ARC001 A - センター採点

解答例
input()
C=input()
print(*sorted(C.count(c) for c in "1234")[::-3])
解答例
input()
C=input()
l=[C.count(c) for c in "1234"]
print(max(l),min(l))
解答例
input()
C=input()
a=C.count("1")
b=C.count("2")
c=C.count("3")
d=C.count("4")
print(max(a,b,c,d),min(a,b,c,d))

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")))

ABC015 B - 高橋くんの集計

解答例
import math
N=int(input())
A=list(map(int,input().split()))
print(math.ceil(sum(A)/(N-A.count(0))))

ABC028 B - 文字数カウント

解答例
s=input()
print(s.count("A"),s.count("B"),s.count("C"),s.count("D"),s.count("E"),s.count("F"))

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

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

ABC091 B - Two Colors Card Game

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

ABC150 B - Count ABC

解答例
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")

ABC084 B - Postal Code

解答例
a,b=map(int,input().split())
s=input()
print("Yes" if s[a]=="-" and s.count("-")==1 else "No")

ABC081 A - Placing Marbles

解答例
print(input().count("1"))

ABC095 A - Something on It

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

ABC101 A - Eating Symbols Easy

解答例
print(2*input().count("+")-4)
解答例
s=input()
print(s.count("+")-s.count("-"))

ABC132 A - Fifty-Fifty

解答例
S=input()
s=list(set(S))
print("Yes" if len(s)==2 and S.count(s[0])==S.count(s[1])==2 else "No")

要素の連結

サンプルコード
List=["ab","cd","ef"]
print("".join(List))
実行結果
abcdef

ARC045 A - スペース高橋君

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

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])

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

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

ABC063 B - Varied

解答例
s=input()
print("no" if len(s)-len(set(s)) else "yes")

ABC085 B - Kagami Mochi

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

ABC033 A - 暗証番号

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

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

解答例
print(len(set(input().split())))

ABC093 A - abc of ABC

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

ABC132 A - Fifty-Fifty

解答例
S=input()
s=list(set(S))
print("Yes" if len(s)==2 and S.count(s[0])==S.count(s[1])==2 else "No")

ABC152 A - AC or WA

解答例
NM=input().split()
print("Yes" if len(set(NM))==1 else "No")

ABC155 A - Poor

解答例
ABC=input().split()
print("Yes" if len(set(ABC))==2 else "No")

ABC158 A - Station and Bus

解答例
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']

ARC005 A - 大好き高橋君

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

ARC049 A - "強調"

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

ABC122 C - GeT AC

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

ABC153 C - Fennec vs Monster

解答例
N,K=map(int,input().split())
H=sorted(map(int,input().split()))[::-1]
print(sum(H[K:]))

ABC011 B - 名前の確認

解答例
s=input()
print(s[0].upper()+s[1:].lower())

ABC026 B - N重丸

解答例
r=sorted(int(input())**2 for i in range(int(input())))[::-1]
print((sum(r[::2])-sum(r[1::2]))*355/113)

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

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

ABC066 B - ss

解答例
s=input()[:-1]
while s[:len(s)//2]!=s[len(s)//2:]:s=s[:-1]
print(len(s))
解答例
s=list(input())
while len(s)!=0:
    s.pop()
    if len(s)%2==0 and s[:len(s)//2]==s[len(s)//2:]:
        print(len(s))
        exit()

ABC067 B - Snake Toy

解答例
n,k=map(int,input().split())
print(sum(sorted(map(int,input().split()))[-k:]))
解答例
n,k=map(int,input().split())
print(sum(sorted(map(int,input().split()))[::-1][:k]))

ABC072 B - OddString

解答例
print(input()[::2])

ABC088 B - Card Game for Two

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

ABC093 B - Small and Large Integers

解答例
a,b,k=map(int,input().split())
r=range(a,b+1)
for i in sorted(set(r[:k])|set(r[-k:])):print(i)

ABC098 B - Cut and Count

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

ABC114 B - 754

解答例
s=input()
print(min(abs(int(s[i:i+3])-753) for i in range(len(s))))

ABC115 B - Christmas Eve Eve

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

ABC117 B - Polygon

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

ABC129 B - Balance

解答例
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)

ABC141 B - Tap Dance

解答例
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")

ABC145 B - Echo

解答例
N=int(input())
S=input()
print("Yes" if S[:N//2]==S[N//2:] else "No")

ABC150 B - Count ABC

解答例
N=int(input())
S=input()
print(sum(S[i:i+3]=="ABC" for i in range(N-2)))

ABC064 A - RGB Cards

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

ABC066 A - ringring

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

ABC085 A - Already 2018

解答例
print("2018"+input()[4:])

リスト内包表記

サンプルコード
List=[i for i in range(5)]
print(List)
実行結果
[0, 1, 2, 3, 4]
サンプルコード
A=[2,4,6,8,10]
A=[a//2 for a in A]
print(A)
実行結果
[1, 2, 3, 4, 5]

ABC081 B - Shift only

解答例
input()
A=list(map(int,input().split()))
ans=0
while all(a%2==0 for a in A):
    A=[a/2 for a in A]
    ans+=1
print(ans)
  • ネスト
サンプルコード
List=[1*i + 10*j + 100*k for k in range(2) for j in range(3) for i in range(4)]
print(List)
実行結果
[0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 100, 101, 102, 103, 110, 111, 112, 113, 120, 121, 122, 123]

ABC051 B - Sum of Three Integers

解答例
k,s=map(int,input().split())
print(len([1 for z in range(k+1) for y in range(k+1) if 0<=s-y-z<=k]))
解答例(TLE)
k,s=map(int,input().split())
print([x+y+z for z in range(k+1) for y in range(k+1) for x in range(k+1)].count(s))

ABC087 B - Coins

解答例
a,b,c,x=[int(input()) for _ in range(4)]
print([500*x+100*y+50*z for z in range(c+1) for y in range(b+1) for x in range(a+1)].count(x))

ABC105 B - Cakes and Donuts

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

要素のソート

サンプルコード
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]

ABC128 B - Guidebook

解答例
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

要素の探索

ABC054 C - One-stroke Path

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

4.6 dict

要素の探索

ARC012 A - 週末

解答例
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()])

ABC036 C - 座圧

解答例
N=int(input())
A=[int(input()) for i in range(N)]
B={a:i for (i,a) in enumerate(sorted(set(A)))}
for a in A:
    print(B[a])
解答例
import bisect
N=int(input())
A=[int(input()) for i in range(N)]
B=sorted(list(set(A)))
for a in A:
    print(bisect.bisect_left(B,a))

ABC137 C - Green Bin

解答例
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()))

ABC155 C - Poll

解答例(TLE)
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)
解答例(TLE)
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())

ABC119 B - Digital Gifts

解答例
XU=[input().split() for i in range(int(input()))]
print(sum([float(x)*{"JPY":1,"BTC":380000}[u] for x,u in XU]))

ABC141 A - Weather Prediction

解答例
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()])

ABC154 A - Remaining Balls

解答例
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

  • 集合型
  • set:オブジェクトの順序なしコレクション

A \cup B
AB
サンプルコード
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
AB
サンプルコード
print({"a","b","c"}-{"c","d","e"})
実行結果
{'a', 'b'}

ABC071 B - Not Found

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

ABC148 A - Round One

解答例
u={1,2,3}
AB=[int(input()) for i in range(2)]
print(list(u-set(AB))[0])

A \cap B
AB
サンプルコード
print({"a","b","c"}&{"c","d","e"})
実行結果
{'c'}

ABC079 C - Cat Snuke and a Voyage

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

ABC098 B - Cut and Count

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

ABC118 B - Foods Loved by Everyone

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

対称差

A ? B
A?B
サンプルコード
print({"a","b","c"}^{"c","d","e"})
実行結果
{'a', 'b', 'e', 'd'}

ABC073 C - Write and Erase

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

ABC071 B - Not Found

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

ABC027 A - 長方形

解答例
print(eval(input().replace(" ","^")))

ABC075 A - One out of Three

解答例
print(eval(input().replace(" ","^")))

部分集合

A \subseteq B
AB
サンプルコード
print({"a","b"}<={"a","b","c"})
実行結果
True
サンプルコード
print({"a","d"}<={"a","b","c"})
実行結果
False

ABC062 A - Grouping

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

文字の集合

サンプルコード
import string
letters=string.ascii_lowercase
print(letters)
実行結果
abcdefghijklmnopqrstuvwxyz
サンプルコード
print(sorted(map(chr,range(97,123))))
実行結果
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
サンプルコード
print(sorted(map(chr,range(65,91))))
実行結果
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

ABC071 B - Not Found

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

ABC093 B - Small and Large Integers

解答例
a,b,k=map(int,input().split())
r=range(a,b+1)
for i in sorted(set(r[:3])|set(r[-3:])):
    print(i)

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}

ABC131 B - Bite Eating

解答例
N,L=map(int,input().split())
taste=range(L,L+N)
print(sum(taste)-min(taste,key=abs))

ABC137 B - One Clue

解答例
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))

ABC114 B - 754

解答例
s=input()
print(min(abs(int(s[i:i+3])-753) for i in range(len(s))))

ABC071 A - Meal Delivery

解答例
x,a,b=map(int,input().split())
print("A" if abs(a-x)<abs(b-x) else "B")

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")

ABC081 B - Shift only

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

ABC109 B - Shiritori

解答例
n=int(input())
w=[input() for i in range(n)]
flag=False
if n==len(set(w)):
    if all([w[i-1][-1]==w[i][0] for i in range(1,n)]):
        flag=True
print("Yes" if flag else "No")

ABC155 B - Papers, Please

解答例
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")

ABC131 A - Security

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

ABC131 A - Security

S=input()
print("Bad" if any(S[i]==S[i+1] for i in range(3)) else "Good")

ABC060 B - Choose Integers

解答例
a,b,c=map(int,input().split())
print("YES" if any((a*i)%b==c for i in range(1,b+1)) else "NO")

5.4 bin/oct/hex

  • bin():整数を先頭に0bが付いた2進文字列に変換する
  • oct():整数を先頭に0oが付いた8進文字列に変換する
  • hex():整数を先頭に0xが付いた16進文字列に変換する

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

ABC105 C - Base -2 Number

解答例
n=int(input())
x=""
while n!=0:
    x=str(n%2)+x
    n=-(n//2)
print(0 if x=="" else x)

ABC068 B - Break Number

解答例
print(2**(len(bin(int(input())))-3))

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

ABC041 C - 背の順

解答例
N=int(input())
A=[(int(a), i) for i,a in enumerate(input().split(),1)]
for a in sorted(A,reverse=True):
    print(a[1])

ABC102 C - Linear Approximation

解答例
N=int(input())
A=sorted(a-i-1 for i,a in enumerate(map(int,input().split())))
print(sum(abs(a-A[N//2]) for a in A))

5.7 eval

サンプルコード
print(eval("1+2"))
実行結果
3

ARC018 A - BMI

解答例
print(eval(input().replace(" ","**2*"))/1e4)

ABC041 B - 直方体

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

ABC073 B - Theater

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

ABC016 A - 12月6日

解答例
print("NO" if eval(input().replace(" ","%")) else "YES")

ABC017 A - プロコン

解答例
print(sum(eval(input().replace(" ","*")) for i in range(3))//10)

ABC035 A - テレビ

解答例
print("4:3" if eval(input().replace(" ","*"))%144 else "16:9")

ABC050 A - Addition and Subtraction Easy

解答例
print(eval(input()))

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

ABC154 C - Distinct or Not

解答例
N=int(input())
A=set(map(int,input().split()))
print("YES" if N==len(A) else "NO")

ABC063 B - Varied

解答例
s=input()
print("no" if len(s)-len(set(s)) else "yes")

ABC069 B - i18n

解答例
s=input()
print(s[0]+str((len(s)-2))+s[-1])

ABC154 B - I miss you...

解答例
print("x"*len(input()))

ABC015 A - 高橋くんの研修

解答例
print(max(input(),input(),key=len))

ABC033 A - 暗証番号

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

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

解答例
print(len(set(input().split())))

ABC093 A - abc of ABC

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

ABC132 A - Fifty-Fifty

解答例
S=input()
s=list(set(S))
print("Yes" if len(s)==2 and S.count(s[0])==S.count(s[1])==2 else "No")

ABC158 A - Station and Bus

解答例
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))

ABC115 B - Christmas Eve Eve

解答例
N=int(input())
p=[int(input()) for i in range(N)]
print(sum(p)-max(p)//2)

ABC149 B - Greedy Takahashi

解答例
A,B,K=map(int,input().split())
print(max(0,A-K),max(0,B-max(0,K-A)))

ABC151 B - Achieve the Goal

解答例
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)

ABC002 A - 正直者

解答例
print(max(map(int,input().split())))

ABC015 A - 高橋くんの研修

解答例
print(max(input(),input(),key=len))

ABC037 A - 饅頭

解答例
a,b,c=map(int,input().split())
print(max(c//a,c//b))

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

解答例
n,k,x,y=[int(input()) for i in range(4)]
print(n*x-(x-y)*max(n-k,0))

ABC052 A - Two Rectangles

解答例
a,b,c,d=map(int,input().split())
print(max(a*b,c*d))

ABC098 A - Add Sub Mul

解答例
a,b=map(int,input().split())
print(max(a+b,a-b,a*b))

ABC100 A - Happy Birthday!

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

ABC103 A - Task Scheduling Problem

解答例
A=list(map(int,input().split()))
print(max(A)-min(A))

ABC117 B - Polygon

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

ABC124 A - Buttons

解答例
a,b=map(int,input().split())
print(max(2*a-1,2*b-1,a+b))

ABC136 A - Transfer

解答例
A,B,C=map(int,input().split())
print(max(0,C-A+B))

ABC137 A - +-x /

解答例
A,B=map(int,input().split())
print(max(A+B,A-B,A*B))

ABC143 A - Curtain

解答例
A,B=map(int,input().split())
print(max(0,A-2*B))

ABC144 A - 9x9

解答例
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

ABC140 C - Maximal Value

解答例
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)))

ABC152 C - Low Elements

解答例
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)

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

解答例
n=int(input())
print(min(int(input()) for i in range(n)))

ABC013 B - 錠

解答例
x=abs(int(input())-int(input()))
print(min(x,10-x))

ABC064 B - Traveling AtCoDeer Problem

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

ABC076 B - Addition and Multiplication

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

ABC094 B - Toll Gates

解答例
n,m,x=map(int,input().split())
s=sum(int(i)<x for i in input().split())
print(min(s,m-s))

ABC113 B - Palace

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

ABC131 B - Bite Eating

解答例
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))

ABC152 B - Comparing Strings

解答例
a,b=input().split()
print(min(a*int(b),b*int(a)))

ABC158 B - Count Balls

解答例
N,A,B=map(int,input().split())
div=N//(A+B)
mod=N%(A+B)
print(div*A+min(mod,A))

ABC037 A - 饅頭

解答例
a,b,c=map(int,input().split())
print(c//min(a,b))

ABC040 A - 赤赤赤赤青

解答例
n,x=map(int,input().split())
print(min(x-1,n-x))

ABC066 A - ringring

解答例
a,b,c=map(int,input().split())
print(min(a+b,b+c,c+a))

ABC080 A - Parking

解答例
n,a,b=map(int,input().split())
print(min(n*a,b))

ABC092 A - Traveling Budget

解答例
a,b,c,d=[int(input()) for _ in range(4)]
print(min(a,b)+min(c,d))

ABC103 A - Task Scheduling Problem

解答例
A=list(map(int,input().split()))
print(max(A)-min(A))

ABC120 A - Favorite Sound

解答例
a,b,c=map(int,input().split())
print(min(c,b//a))

ABC129 A - Airplane

解答例
P,Q,R=map(int,input().split())
print(min(P+Q,Q+R,R+P))

ABC133 A - T or T

解答例
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']

ABC146 B - ROT N

解答例
N=int(input())
S=input()
print("".join(chr(65+(ord(s)-65+N)%26) for s in S))

ABC013 A - A

解答例
print(ord(input())-64)

ABC151 A - Next Alphabet

解答例
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():べき乗を返す

ABC034 C - 経路

解答例
from math import factorial
W,H=map(int,input().split())
m=10**9+7
print(factorial(W+H-2)*pow(factorial(H-1)*factorial(W-1)%m,m-2,m)%m)

ABC134 A - Dodecagon

解答例
print(3*pow(int(input()),2))

ABC140 A - Password

解答例
print(pow(int(input()),3))

ABC145 A - Circle

解答例
print(pow(int(input()),2))

5.14 sorted

  • sorted():iterable の要素を並べ替えた新たなリストを返す

ARC042 A - 掲示板

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

ABC004 C - 入れ替え

解答例
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)

ABC113 C - ID

解答例
import collections
import bisect
n,m=map(int,input().split())
p=[[int(j) for j in input().split()] for i in range(m)]
a=collections.defaultdict(list)
for x,y in sorted(p):
    a[x]+=[y]
for x,y in p:
    z=bisect.bisect(a[x],y)
    print("%06d%06d"%(x,z))

ABC134 C - Exception Handling

解答例
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)

ABC153 C - Fennec vs Monster

解答例
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])

ABC026 B - N重丸

解答例
r=sorted(int(input())**2 for i in range(int(input())))[::-1]
print((sum(r[::2])-sum(r[1::2]))*355/113)

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

n,l=map(int,input().split())
s=sorted([input() for i in range(n)])
print(*s,sep="")
n,l=map(int,input().split())
s=sorted([input() for i in range(n)])
print("".join(s))

ABC064 B - Traveling AtCoDeer Problem

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

ABC067 B - Snake Toy

解答例
n,k=map(int,input().split())
print(sum(sorted(map(int,input().split()))[-k:]))
解答例
n,k=map(int,input().split())
print(sum(sorted(map(int,input().split()))[::-1][:k]))

ABC102 B - Maximum Difference

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

ABC117 B - Polygon

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

ABC018 A - 豆まき

解答例
X=[int(input()) for i in range(3)]
for x in X:print(3-sorted(X).index(x))
解答例
l=[int(input()) for _ in range(3)]
s=sorted(l)[::-1]
for i in l:
    print(s.index(i)+1)

ABC019 A - 高橋くんと年齢

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

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

解答例
a,b,c=sorted(map(int,input().split()))
print("Yes" if a+b==c else "No")
解答例
l=sorted(map(int,input().split()))
print("Yes" if sum(l[:2])==l[2] else "No")

ABC066 A - ringring

解答例
a,b,c=sorted(map(int,input().split()))
print(a+b)

ABC103 A - Task Scheduling Problem

解答例
a,b,c=sorted(map(int,input().split()))
print(c-a)

ABC110 A - Maximize the Formula

解答例
print(eval("+".join(sorted(input()))+"*10"))
解答例
A,B,C=sorted(map(int,input().split()))
print(10*C+B+A)

5.15 sum

  • sum():合計を返す

ABC140 C - Maximal Value

解答例
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)))

ABC143 C - Slimes

解答例
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))))

ABC015 B - 高橋くんの集計

解答例
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)))

ABC067 B - Snake Toy

解答例
n,k=map(int,input().split())
print(sum(sorted(map(int,input().split()))[-k:]))
解答例
n,k=map(int,input().split())
print(sum(sorted(map(int,input().split()))[::-1][:k]))

ABC115 B - Christmas Eve Eve

解答例
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]))

ABC117 B - Polygon

解答例
input()
L=list(map(int,input().split()))
print("Yes" if sum(L)>2*max(L) else "No")
解答例
input()
L=sorted(map(int,input().split()))[::-1]
print("Yes" if L[0]<sum(L[1:]) else "No")

ABC131 B - Bite Eating

解答例
N,L=map(int,input().split())
taste=[L+i for i in range(N)]
print(sum(taste)-min(taste,key=abs))

ABC142 B - Roller Coaster

解答例
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))

ABC147 B - Palindrome-philia

解答例
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")

ABC017 A - プロコン

解答例
print(sum(eval(input().replace(" ","*")) for i in range(3))//10)

ABC063 A - Restricted

解答例
x=sum(map(int,input()[::2]))
print(x if x<10 else "error")

ABC066 A - ringring

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

ABC139 A - Tenki

解答例
S=input()
T=input()
print(sum(s==t for s,t in zip(S,T)))

ABC147 A - Blackjack

解答例
A=map(int,input().split())
print("bust" if sum(A)>=22 else "win")

数字和

サンプルコード
string="1234"
print(sum(map(int,string)))
実行結果
10 # 1+2+3+4

ABC080 B - Harshad Number

ハーシャッド数 - Wikipedia

  • 各位の数字和が元の数の約数にある自然数
解答例
n=input()
print("No" if int(n)%sum(map(int,n)) else "Yes")

ABC083 B - Some Sums

解答例
n,a,b=map(int,input().split())
print(sum(i for i in range(n+1) if a<=sum(map(int,str(i)))<=b))
解答例
n,a,b=map(int,input().split())
ans=0
for i in range(n+1):
    if a<=sum(map(int,str(i)))<=b:ans+=i
print(ans)
解答例
n,a,b=map(int,input().split())
s=0
for i in range(n+1):
    if a<=sum(int(j) for j in str(i))<=b:
        s+=i
print(s)
解答例
n,a,b=map(int,input().split())
s=0
for i in range(n+1):
    c=0
    d=str(i)
    for j in range(len(d)):
        c+=int(d[j])
    if a<=c<=b:
        s+=i
print(s)

ABC101 B - Digit Sums

解答例
N=input()
print("Yes" if int(N)%sum(map(int,list(N)))==0 else "No")
解答例
N=input()
print("Yes" if int(N)%sum(int(_) for _ in N)==0 else "No")
解答例
N=input()
s=0
for n in N:
    s+=int(n)
print("Yes" if int(N)%s==0 else "No")

ABC023 A - 加算王

解答例
print(sum(map(int,input())))

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]]

ARC025 A - ゴールドラッシュ

解答例
print(sum(map(max,zip(*[list(map(int,input().split())) for i in range(2)]))))
解答例
D=map(int,input().split())
J=map(int,input().split())
print(sum(max(d,j) for d,j in zip(D,J)))

ABC157 C - Guess The Number

解答例
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)

ABC058 B - ∵∴∵

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

ABC121 B - Can you solve this?

解答例
N,M,C=map(int,input().split())
B=list(map(int,input().split()))
count=0
for i in range(N):
    A=list(map(int,input().split()))
    if sum(a*b for a,b in zip(A,B))+C>0:count+=1
print(count)

ABC147 B - Palindrome-philia

解答例
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="")

ABC139 A - Tenki

解答例
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
                                       ^
"""

ABC119 D - Lazy Faith

解答例
import bisect
A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
    x=int(input())
    i=bisect.bisect_right(S,x)
    j=bisect.bisect_right(T,x)
    d=INF
    for s in [S[i-1],S[i]]:
        for t in [T[j-1],T[j]]:
            d1=abs(s-x)+abs(s-t)
            d2=abs(t-x)+abs(s-t)
            d=min(d,d1,d2)
    print(d)

ABC084 C - Snuke Festival

解答例
import bisect
N=int(input())
A=sorted(list(map(int,input().split())))
B=sorted(list(map(int,input().split())))
C=sorted(list(map(int,input().split())))
print(sum(bisect.bisect_left(A,b)*(N-bisect.bisect_right(C,b)) for b in B))
解答例
from collections import Counter
N=int(input())
A=Counter(input().split())
B=Counter(input().split())
C=Counter(input().split())
ans=0
for a_key,a_count in A.most_common():
    for b_key,b_count in B.most_common():
        for c_key,c_count in C.most_common():
            a_key,b_key,c_key=int(a_key),int(b_key),int(c_key)
            if a_key<b_key and b_key<c_key:
                ans+=a_count*b_count*c_count
print(ans)

ABC130 B - Bounding

解答例
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

ARC002 A - うるう年

解答例
import calendar
print("YES" if calendar.isleap(int(input())) else "NO")

6.3 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

ARC024 A - くつがくっつく

解答例
from collections import Counter
input()
L=Counter(input().split())
R=Counter(input().split())
print(sum([min(value,L[key]) for key,value in R.items()]))

ARC081 C - Make a Rectangle

解答例
from collections import Counter
N=int(input())
A=Counter(list(map(int,input().split())))
x=[0,0]
for a in A:
    if A[a]>1:x.append(a)
    if A[a]>3:x.append(a)
x.sort()
print(x[-1]*x[-2])

ABC071 C - 怪文書 / Dubious Document

解答例
from collections import Counter
n=int(input())
s=Counter(input())
for i in range(n-1):
    s&=Counter(input())
print("".join(sorted(s.elements())))

ABC073 C - Write and Erase

解答例
from collections import Counter
N=int(input())
A=Counter([int(input()) for i in range(N)])
print(sum(1 if count%2 else 0 for count in A.values()))

ABC081 C - Not so Diverse

解答例
from collections import Counter
n,k=map(int,input().split())
a=Counter(input().split())
print(sum(sorted(a.values(),reverse=True)[k:]))
解答例
from collections import Counter
n,k=map(int,input().split())
a=Counter(input().split())
ans=0
keys,counts=zip(*a.most_common())
for num,(key,count) in enumerate(zip(keys,counts)):
    if int(num)>k-1:ans+=count
print(ans)

ABC082 C - Good Sequence

解答例
from collections import Counter
n=int(input())
a=Counter(input().split())
ans=0
for i,j in a.items():
    i=int(i)
    if i>j:
        ans+=j
    elif i<j:
        ans+=j-i
print(ans)

ABC103 C - /\/\/\/

解答例
from collections import Counter
n=int(input())
v=list(map(int,input().split()))
a=Counter(v[0::2]).most_common()
b=Counter(v[1::2]).most_common()
a.append([0,0])
b.append([0,0])
if a[0][0]!=b[0][0]:
    print(n-(a[0][1]+b[0][1]))
else:
    print(min(n-(a[1][1]+b[0][1]),n-(a[0][1]+b[1][1])))

ABC110 C - String Transformation

解答例
from collections import Counter
s=Counter(list(input()))
t=Counter(list(input()))
s,t=list(s.values()),list(t.values())
print("Yes" if sorted(s)==sorted(t) else "No")

ABC137 C - Green Bin

解答例
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()))

ABC008 B - 投票

解答例
from collections import Counter
print(Counter([input() for i in range(int(input()))]).most_common()[0][0])

ABC132 A - Fifty-Fifty

解答例
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

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

ABC109 C - Skip

解答例
from functools import reduce
from fractions import gcd
N,X=map(int,input().split())
x=[abs(X-int(i)) for i in input().split()]
print(reduce(gcd,x))

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

ARC081 C - Make a Rectangle

解答例
import heapq
N=int(input())
s=set()
q=[0,0]
for a in map(int,input().split()):
    if a>q[0]:
        try:
            s.remove(a)
            heapq.heapreplace(q,a)
        except:
            s.add(a)
print(q[0]*q[1])

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通り
4C2=4P22!=6
サンプル
from itertools import combinations
List=["a","b","c","d"]
print(list(combinations(List,2)))
# [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
print(len(list(combinations(List,2))))
# 6

ABC028 C - 数を3つ選ぶマン

解答例
from itertools import combinations
S=map(int,input().split())
print(sorted(map(sum,combinations(S,3)))[-3])

ABC089 C - March

サンプルコード
from itertools import combinations
for a,b,c in combinations("MARCH",3):
    print(a,b,c)
実行結果
M A R
M A C
M A H
M R C
M R H
M C H
A R C
A R H
A C H
R C H
解答例
from itertools import combinations
from collections import Counter
N=int(input())
S=Counter()
for i in range(N):
    S[input()[0]]+=1
print(sum([S[a]*S[b]*S[c] for a,b,c in combinations("MARCH",3)]))

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)

ABC143 C - Slimes

解答例
import itertools
N=int(input())
S=input()
print(len(list(itertools.groupby(S))))

ABC019 B - 高橋くんと文字列圧縮

解答例
import itertools
print("".join([i+str(len(list(j))) for i,j in itertools.groupby(list(input()))]))
解答例
import itertools
s=""
for i,j in itertools.groupby(list(input())):
    s+=i+str(len(list(j)))
print(s)

permutations

4! = 4 × 3 × 2 × 1 = 24通り
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通り
4P2=4×3=12
サンプルコード
from itertools import permutations
List=["a","b","c"]
print(list(permutations(List,2)))
print(len(list(permutations(List,2))))
実行結果
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]
12

ARC013 A - 梱包できるかな?

解答例
from itertools import permutations
n,m,l=map(int,input().split())
P=list(map(int,input().split()))
v=0
for p,q,r in permutations(P):
    v=max(v,(n//p)*(m//q)*(l//r))
print(v)

ABC150 C - Count Order

解答例
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))))

ABC123 B - Five Dishes

解答例
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

ABC029 C - Brute-force Attack

解答例
from itertools import product
[print("".join(i)) for i in product("abc",repeat=int(input()))]

ABC114 C - 755

解答例
import itertools
N=int(input())
ans=0
S=[]
for i in range(10):
    S+=list(itertools.product("357",repeat=i))
for s in S:
    if len(set(s))>2 and int("".join(s))<=N:
        ans+=1
print(ans)

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))

ABC055 B - Training Camp

解答例
import math
print(math.factorial(int(input()))%(10**9+7))

ABC134 B - Golden Apple

解答例
import math
N,D=map(int,input().split())
print(math.ceil(N/(D*2+1)))

floor

サンプルコード
import math
print(math.floor(5/3))
実行結果
1
サンプルコード
import math
print(math.floor(6/3))
実行結果
2

log

ABC156 B - Digits

解答例
import math
N,K=map(int,input().split())
print(int(math.log(N,K))+1)

sqrt

サンプルコード
import math
print(math.sqrt(4))
実行結果
2.0

6.9 numpy

argsort

ABC004 C - 入れ替え

解答例
import numpy
N=int(input())
A=list(map(int,input().split()))
print(*numpy.argsort(A)+1)

array

ABC133 B - Good Distance

解答例
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

ABC133 B - Good Distance

解答例
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()))

ABC145 C - Average Length

解答例
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 による重複しないマッチを文字列のリストとして返す

ABC122 B - ATCoder

解答例
import re
print(max(map(len,re.findall("[ACGT]*",input()))))

ARC052 A - 何期生?

解答例
import re
print(*re.findall("[0-9]+",input()))

match

ABC049 C - 白昼夢 / Daydream

解答例
import re
print("YES" if re.match("^(dream|dreamer|erase|eraser)+$",input()) else "NO")

ABC076 C - Dubious Document 2

解答例
import re
s=input().replace("?",".")
t=input()
for i in range(len(s)-len(t),-1,-1):
    if re.match(s[i:i+len(t)],t):
        s=s.replace(".","a")
        print(s[:i]+t+s[i+len(t):])
        exit()
print("UNRESTORABLE")
解答例
import re
s=input().replace("?",".")
t=input()
for i in range(len(s)-len(t)+1):
    if re.match(s[i:i+len(t)],t):
        s=s.replace(".","a")
        print(s[:i]+t+s[i+len(t):])
        exit()
print("UNRESTORABLE")

ABC023 B - 手芸王

解答例
import re
n=int(input())
f=re.match(r"^((bcabca)*b|(cabcab)*cabca|(abcabc)*abc)$",input())
print(n//2 if f else -1)

ABC104 B - AcCepted

解答例
import re
print("AC" if re.match("^A[a-z]+C[a-z]+$",input()) else "WA")

search

ARC022 A - スーパーICT高校生

解答例
import re
print("YES" if re.search("i.*c.*t",input().lower()) else "NO")
解答例
import re
print("YES" if re.search("[i|I].*[c|C].*[t|T]",input()) else "NO")

split

  • re.split():string を pattern で分割し、リストを返す

ABC122 B - ATCoder

解答例
import re
print(max(map(len,re.split("[^ACGT]",input()))))

sub

  • re.sub():string を重複しない pattern を置換した文字列を返す

ARC052 A - 何期生?

解答例
import re
print(re.sub("\D","",input()))

ABC002 B - 罠

解答例
import re
print(re.sub("[aiueo]","",input()))

ABC017 B - choku語

解答例
import re
print("NO" if re.sub(r"ch|o|k|u","",input()) else "YES")

第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

ABC120 C - Unification

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

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

解答例
t=""
for x in input():
    if x=="B":t=t[:-1]
    else:t+=x
print(t)
解答例
t=[]
for x in input():
    if x=="B":
        try:t.pop()
        except:pass
    else:t.append(x)
print("".join(t))

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

ABC077 C - pushpush

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

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

解答例
S={c:list(input()) for c in "abc"}
s="a"
while S[s]:s=S[s].pop(0)
print(s.upper())

第8章 アルゴリズム観点

ユークリッドの互除法

  • 2つの自然数の最大公約数を求める手法

ユークリッドの互除法 - Wikipedia

サンプルコード
a,b=12,8
x,y=max(a,b),min(a,b)
while y!=0:x,y=y,x%y
print(x)
実行結果
4

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

解答例
a,b,n=[int(input()) for i in range(3)]
while n%a!=0 or n%b!=0:n+=1
print(n)

最大公約数(GCD)

  • GCD:Greatest Common Divisor
サンプルコード
from functools import reduce
from fractions import gcd
List=[15,25,30]
print(reduce(gcd,List))
実行結果
5

ABC109 C - Skip

解答例
from functools import reduce
from fractions import gcd
N,X=map(int,input().split())
x=[abs(X-int(i)) for i in input().split()]
print(reduce(gcd,x))

ABC118 C - Monsters Battle Royale

解答例
import functools
import fractions
N=int(input())
A=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,A))

ABC131 C - Anti-Division

解答例
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

ABC070 C - Multiple Clocks

解答例
from fractions import gcd
def lcm(a,b): return a*b//gcd(a,b)
N=int(input())
ans=1
for i in range(N):
    t=int(input())
    ans=lcm(ans,t)
print(ans)

ABC118 C - Monsters Battle Royale

解答例
import functools
import fractions
N=int(input())
A=list(map(int,input().split()))
print(functools.reduce(fractions.gcd,A))

ABC131 C - Anti-Division

解答例
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))

ABC148 C - Snack

解答例
import fractions
A,B=map(int,input().split())
print(A*B//fractions.gcd(A,B))

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

解答例
a,b,n=[int(input()) for i in range(3)]
while n%a!=0 or n%b!=0:n+=1
print(n)

探索

全探索

ARC036 A - ぐっすり

解答例
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)

ABC080 C - Shopping Street

解答例
N=int(input())
F=[int(input().replace(" ",""),2) for i in range(N)]
P=[list(map(int,input().split())) for i in range(N)]
print(max(sum([p[bin(f&i).count("1")] for f,p in zip(F,P)]) for i in range(1,2**10)))

ABC107 C - Candles

解答例
n,k=map(int,input().split())
x=sorted(list(map(int,input().split())))
print(min((min(abs(x[i])+abs(x[i+k-1]-x[i]),abs(x[i+k-1])+abs(x[i]-x[i+k-1]))) for i in range(n-k+1)))
解答例
n,k=map(int,input().split())
x=sorted(list(map(int,input().split())))
a=[]
for i in range(n-k+1):
    l=x[i]
    r=x[i+k-1]
    a.append(min(abs(l)+abs(r-l),abs(r)+abs(l-r)))
print(min(a))

ABC123 B - Five Dishes

解答例
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)

ARC029 A - 高橋君とお肉

解答例
N=int(input())
T=sorted(int(input()) for i in range(N))[::-1]
x=y=0
for t in T:
    if x<y:x+=t
    else:y+=t
print(max(x,y))

ARC041 A - コインの反転

解答例
x,y=map(int,input().split())
k=int(input())
print(x+y-abs(k-y))

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

深さ優先探索 - Wikipedia

ABC114 C - 755

解答例
N = int(input())
def dfs(s):
    if int(s)>N:
        return 0;
    ret = 1 if all(s.count(c) > 0 for c in "753") else 0
    for c in "753":
        ret += dfs(s+c)
    return ret
print(dfs("0"))

ATC001 A - 深さ優先探索

解答例
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")
  • 未解答

ABC054 C - One-stroke Path

幅優先探索(BFS)

  • BFS:Breadth First Search

幅優先探索 - Wikipedia

ABC007 C - 幅優先探索

bit全探索

ABC128 C - Switches

解答例
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)

ABC147 C - HonestOrUnkind2

解答例
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)

シミュレーション

ARC010 A - 名刺交換

解答例
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")

ABC135 C - City Savers

解答例
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)

ABC139 B - Power Socket

解答例
A,B=map(int,input().split())
count,outlet=0,1
while(outlet<B):
    outlet-=1
    outlet+=A
    count+=1
print(count)

ABC141 C - Attack Survival

解答例
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")

ABC151 C - Welcome to AtCoder

解答例
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)

ABC140 B - Buffet

解答例
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)

ABC011 C - 123引き算

解答例
N=int(input())
NG=[int(input()) for i in range(3)]
if N in NG:
    print("NO")
    exit()
for i in range(100):
    N-=3
    if N in NG:
        N+=1
        if N in NG:
            N+=1
            if N in NG:
                print("NO")
                exit()
print("YES" if N<=0 else "NO")

ABC048 C - Boxes and Candies

解答例
A=list(map(int,input().split()))+[0]
ans=0
for i in range(N):
    eated=max(0,A[i]+A[i-1]-x)
    ans+=eated
    A[i]-=eated
print(ans)

ABC053 B - A to Z String

解答例
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)

ABC067 B - Snake Toy

解答例
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)

ABC096 B - Maximum Sum

解答例
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))

ABC115 B - Christmas Eve Eve

解答例
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)

ABC123 B - Five Dishes

解答例
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)

ABC142 B - Roller Coaster

解答例
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

動的計画法 - Wikipedia

  • フィボナッチ数列
サンプルコード(再帰関数)
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))
サンプルコード(DP)
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])

ABC129 C - Typical Stairs

解答例
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])
解答例(TLE)
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])

ABC139 C - Lower

解答例
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))

EDPC A - Frog 1

サンプルコード(DP)
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])

ABC118 D - Match Matching

解答例
N,M=map(int,input().split())
A=list(map(int,input().split()))
d=[0]*N*9+[-1]*N*9
for i in range(1,N+1):d[i]=max(d[i-int("0255456376"[a])]*10+a for a in A)
print(d[N])
解答例
N,M=map(int,input().split())
A=list(map(int,input().split()))
weight=[0,2,5,5,4,5,6,3,7,6]
dp=[-1]*(N+1)
dp[0]=0
for i in range(N+1):
    for a in A:
        if i+weight[a]<N+1:
            dp[i+weight[a]]=max(dp[i+weight[a]],dp[i]*10+a)
print(dp[N])

ABC040 C - 柱柱柱柱柱

解答例
N=int(input())
A=list(map(int,input().split()))+[0]
dp=[0]*N
dp[1]=abs(A[1]-A[0])
for i in range(1,N-1):
    dp[i+1]=min(dp[i]+abs(A[i+1]-A[i]),dp[i-1]+abs(A[i+1]-A[i-1]))
print(dp[N-1])

ABC011 C - 123引き算

解答例
N=int(input())
NG=[int(input()) for i in range(3)]
dp=[float("INF")]*301
dp[N]=0
for i in range(N,0,-1):
    if i in NG:continue
    for j in range(1,4):
        dp[i-j]=min(dp[i]+1,dp[i-j])
print("YES" if dp[0]<=100 else "NO")
  • 未解答

ABC122 D - We Like AGC
ABC034 C - 経路

UnionFind

素集合データ構造 - Wikipedia

  • 未解答

ABC040 D - 道路の老朽化対策について
ABC120 D - Decayed Bridges
ABC075 C - Bridge
ABC054 C - One-stroke Path
ABC015 C - 高橋くんのバグ探し

しゃくとり法

ABC032 C - 列

解答例
N,K=map(int,input().split())
S=[int(input()) for i in range(N)]
length=left=0
mul=1
if 0 in S:
    length=N
else:
    for right in range(N):
        mul*=S[right]
        if mul<=K:
            length=max(length,right-left+1)
        else:
            mul//=S[left]
            left+=1
print(length)
解答例(TLE)
N,K=map(int,input().split())
S=[int(input()) for i in range(N)]
length=0
if 0 in S:
    length=N
else:
    for i in range(N):
        for j in range(i+1,N):
            mul=1
            for k in range(i,j+1):
                mul*=S[k]
            if mul<=K:
                length=max(length,j-i+1)
print(length)

ABC038 C - 単調増加

解答例
N=int(input())
A=list(map(int,input().split()))
diff=0
ans=N
for i in range(N-1):
    if A[i]<A[i+1]:
        diff+=1
        ans+=diff
    else:
        diff=0
print(ans)

グラフ

ARC030 A - 閉路グラフ

解答例
N=int(input())
K=int(input())
print("YES" if K<=N//2 else "NO")

ABC016 C - 友達の友達

解答例
V,E=map(int,input().split())
edges=[set() for i in range(V)]
for i in range(E):
    a,b=map(int,input().split())
    edges[a-1].add(b-1)
    edges[b-1].add(a-1)
for i in range(V):
    print(len({n for v in edges[i] for n in edges[v] if not n in edges[i] and n!=i}))

ABC054 C - One-stroke Path

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

ABC075 C - Bridge

解答例
N,M=map(int,input().split())
edges=[list(map(int,input().split())) for i in range(M)]
ans=0
for x in edges:
    l=list(range(N))
    for y in edges:
        if y!=x:l=[l[y[0]-1] if l[i]==l[y[1]-1] else l[i] for i in range(N)]
    if len(set(l))!=1:ans+=1
print(ans)

ABC021 B - 嘘つきの高橋くん

解答例
input()
a=input().split()
input()
a+=input().split()
print("YES" if len(a)==len(set(a)) else "NO")

ABC061 B - Counting Roads

解答例
n,m=map(int,input().split())
l=[]
for i in range(m):l+=list(map(int,input().split()))
for i in range(1,n+1):print(l.count(i))
  • 未分類

ABC012 D - バスと避けられない運命
ABC014 D - 閉路
ABC019 D - 高橋くんと木の直径
ABC035 D - トレジャーハント
ABC051 D - Candidates of No Shortest Paths
ABC061 D - Score Attack
ABC070 D - Transit Tree Path
ABC073 D - joisino's travel
ABC074 D - Restoring Road Network

最大フロー

最大フロー問題 - Wikipedia

  • 未分類

ABC010 D - 浮気予防

エラトステネスのふるい

エラトステネスの篩 - Wikipedia

  • 未解答

ABC084 D - 2017-like Number

ワーシャル?フロイド法

ワーシャル?フロイド法 - Wikipedia

  • 未解答

ABC016 C - 友達の友達

クラスカル法/プリム法

クラスカル法 - Wikipedia

プリム法 - Wikipedia

  • 未解答

ARC076 D - Built?

第9章 計算量観点

剰余

ABC055 B - Training Camp

解答例
import math
print(math.factorial(int(input()))%(10**9+7))
解答例
ans=1
n=int(input())
for i in range(1,n+1):
    ans*=i
    ans=ans%(10**9+7)
print(ans)
解答例(TLE)
ans=1
n=int(input())
for i in range(1,n+1):
    ans*=i
print(ans%(10**9+7))

ソート

ABC004 C - 入れ替え

解答例(TLE)
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)

ABC004 C - 入れ替え

解答例
N=int(input())%30
X=[1,2,3,4,5,6]
for i in range(N):
    tmp=X[i%5+1]
    X[i%5+1]=X[i%5]
    X[i%5]=tmp
print(*X,sep="")
解答例(TLE)
N=int(input())
X=[1,2,3,4,5,6]
for i in range(N):
    tmp=X[i%5+1]
    X[i%5+1]=X[i%5]
    X[i%5]=tmp
print(*X,sep="")

つるかめ算

ABC006 C - スフィンクスのなぞなぞ

解答例
N,M=map(int,input().split())
if 2*N<=M<=4*N:
    y=M%2
    z=((M-3*y)-2*(N-y))//2
    x=N-y-z
    print(x,y,z)
else:
    print("-1 -1 -1")
解答例(TLE)
N,M=map(int,input().split())
for x in range(N+1):
    for y in range(N+1):
        z=N-x-y
        if 2*x+3*y+4*z==M and z>=0:
            print(x,y,z)
            exit()
print("-1 -1 -1")

いもす法

ABC017 C - ハイスコア

解答例
n,m=map(int,input().split())
imos=[0]*(m+1)
t=0
for i in range(n):
    l,r,s=map(int,input().split())
    imos[l-1]+=s
    imos[r]-=s
    t+=s
for i in range(m):
    imos[i+1]+=imos[i]
print(t-min(imos[:-1]))

ABC035 C - オセロ

解答例
N,Q=map(int,input().split())
O=[0]*(N+1)
for i in range(Q):
    l,r=map(int,input().split())
    O[l-1]+=1
    O[r]-=1
for i in range(N):
    if i>0:O[i]+=O[i-1]
    print(O[i]%2,end="")
print()
解答例(TLE)
N,Q=map(int,input().split())
O=[0]*N
for i in range(Q):
    l,r=map(int,input().split())
    for j in range(l,r+1):
        O[j-1]+=1
for i in range(N):
    if O[i]%2==0:
        O[i]=0
    else:
        O[i]=1
print(*O,sep="")

ABC014 C - AtColor

解答例
N=int(input())
n=10**6+1
x=[0]*(n+1)
for i in range(N):
    a,b=map(int,input().split())
    x[a]+=1
    x[b+1]-=1
for i in range(n):
    x[i+1]+=x[i]
print(max(x))
  • 未分類

ABC001 D - 感雨時刻の整理

累積和

  • 累積和:Cumulative sum
サンプルコード
List=[0,1,2,3,4,5,6,7,8,9,10]
for i in range(1,len(List)):List[i]+=List[i-1]
print(List)
実行結果
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

ABC067 C - Splitting Pile

解答例
N=int(input())
A=list(map(int,input().split()))
S=sum(A)
T=[0]*N
for i in range(N-1):
    T[i+1]=T[i]+A[i]
print(min(abs(S-2*T[i]) for i in range(1,N)))
解答例(TLE)
N=int(input())
A=list(map(int,input().split()))
print(min(abs(sum(A[:i])-sum(A[i:])) for i in range(1,N)))

ABC098 C - Attention

解答例
N=int(input())
S=input()
cnt=S.count("E")
m=cnt
for i in S:
    if i=="E":
        cnt-=1
    else:
        cnt+=1
    m=min(m,cnt)
print(m)

ABC122 C - GeT AC

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

ABC130 B - Bounding

解答例
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))))
  • 未分類

ABC009 D - 漸化式

二分探索

ABC119 D - Lazy Faith

解答例
import bisect
A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
    x=int(input())
    i=bisect.bisect_right(S,x)
    j=bisect.bisect_right(T,x)
    d=INF
    for s in [S[i-1],S[i]]:
        for t in [T[j-1],T[j]]:
            d1=abs(s-x)+abs(s-t)
            d2=abs(t-x)+abs(s-t)
            d=min(d,d1,d2)
    print(d)

ABC030 C - 飛行機乗り

解答例
import bisect
N,M=map(int,input().split())
X,Y=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
ans=0
time=0
while time<=A[-1]:
    time=A[bisect.bisect_left(A,time)]+X
    if time<=B[-1]:
        time=B[bisect.bisect_left(B,time)]+Y
        ans+=1
    else:break
print(ans)

ABC084 C - Snuke Festival

解答例
import bisect
N=int(input())
A=sorted(list(map(int,input().split())))
B=sorted(list(map(int,input().split())))
C=sorted(list(map(int,input().split())))
print(sum(bisect.bisect_left(A,b)*(N-bisect.bisect_right(C,b)) for b in B))
解答例(TLE)
from collections import Counter
N=int(input())
A=Counter(input().split())
B=Counter(input().split())
C=Counter(input().split())
ans=0
for a_key,a_count in A.most_common():
    for b_key,b_count in B.most_common():
        for c_key,c_count in C.most_common():
            a_key,b_key,c_key=int(a_key),int(b_key),int(c_key)
            if a_key<b_key and b_key<c_key:
                ans+=a_count*b_count*c_count
print(ans)

ABC146 C - Buy an Integer

解答例
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 - 食塩水

中央値の算出

ABC094 C - Many Medians

解答例(TLE)
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

解答例(TLE)
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])

条件式によるループ回数削減

ABC097 B - Exponential

解答例
x=int(input())
c=1
for b in range(1,x):
    for p in range(2,x):
        if b**p<=x:c=max(c,b**p)
        else:break # b**pがx以上は計算を省く
print(c)
解答例(TLE)
x=int(input())
c=1
for b in range(1,x):
    for p in range(2,x):
        if b**p<=x:c=max(c,b**p)
print(c)

処理中の剰余算(10*n+7)

ABC034 C - 経路

解答例
from math import factorial
W,H=map(int,input().split())
m=10**9+7
print(factorial(W+H-2)*pow(factorial(H-1)*factorial(W-1)%m,m-2,m)%m)

ABC065 C - Reconciled?

解答例
import math
N,M=map(int,input().split())
print(max(2-abs(N-M),0)*math.factorial(N)*math.factorial(M)%(10**9+7))

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)

ABC006 B - トリボナッチ数列

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

ABC041 B - 直方体

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

方程式

ABC085 C - Otoshidama

解答例
N,Y=map(int,input().split())
for x in range(N+1):
    for y in range(N-x+1):
        z=N-x-y
        if 0<=z<=2000 and 10000*x+5000*y+1000*z==Y:
            print(x,y,z)
            exit()
print(-1,-1,-1)
解答例
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]))
解答例(TLE)
k,s=map(int,input().split())
print([x+y+z for z in range(k+1) for y in range(k+1) for x in range(k+1)].count(s))

部分数列の総和

ABC037 C - 総和

解答例
N,K=map(int,input().split())
A=list(map(int,input().split()))
print(sum(A[i]*min(i+1,K,N-i,N-K+1) for i in range(N)))
解答例(TLE)
N,K=map(int,input().split())
A=list(map(int,input().split()))
print(sum(sum(A[i:i+K]) for i in range(N-K+1)))

キュー

ABC077 C - pushpush

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

桁数

ABC057 C - Digits in Multiplication

解答例
N=int(input())
i=int(N**(1/2))
while N%i!=0:
    i-=1
print(len(str(N//i)))
解答例
def ketasu(N):
    count=1
    while N>=10:
        N//=10
        count+=1
    return count
N=int(input())
keta=10**10
for i in range(1,int(N**.5)+1):
    if N%i==0:
        keta=min(keta,max(ketasu(i),ketasu(N//i)))
print(keta)

ABC156 B - Digits

解答例
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章 数学観点

和差算

ABC096 B - Maximum Sum

解答例
a,b,c=sorted(map(int, input().split()))
print(a+b+c*2**int(input()))
解答例
l=[int(_) for _ in input().split()]
k=int(input())
print(sum(l)-max(l)+max(l)*2**k)

ABC110 A - Maximize the Formula

解答例
print(eval("+".join(sorted(input()))+"*10"))
解答例
A,B,C=sorted(map(int,input().split()))
print(10*C+B+A)

ABC111 A - AtCoder Beginner Contest 999

解答例
print(1110-int(input()))

数列

ABC050 C - Lining Up

解答例
import math
N=int(input())
A=list(map(int,input().split()))
flag=True
if N%2==0:
    if 0 in A or len(set(A))!=N//2:flag=False
else:
    if len([0 for a in A if a==0])!=1 or len(set(A))!=N//2+1:flag=False
if flag:print(2**(N//2)%(10**9+7))
else:print(0)

ABC059 C - Sequence

解答例
n=input()
a=[int(i) for i in input().split()]
def chk(a,t):
    ans=0
    x=0
    for i in a:
        x+=i
        if t==True and x<1:
            ans+=1-x
            x=1
        elif t==False and x>-1:
            ans+=x+1
            x=-1
        t=not t
    return ans
print(min(chk(a,True),chk(a,False)))

ABC087 C - Candies

解答例
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
print(max(sum(a[:i+1])+sum(b[i:]) for i in range(n)))
解答例
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ans=0
for i in range(n):
    ans=max(ans,sum(a[:i+1])+sum(b[i:]))
print(ans)

ABC092 C - Traveling Plan

解答例
N=int(input())
A=[0]+list(map(int,input().split()))+[0]
cost=sum(abs(A[i+1]-A[i]) for i in range(N+1))
for i in range(1,N+1):
    print(cost-abs(A[i+1]-A[i])-abs(A[i]-A[i-1])+abs(A[i+1]-A[i-1]))
解答例
N=int(input())
A=list(map(int,input().split()))+[0]
A.insert(0,0)
cost=0
for i in range(N+1):
    cost+=abs(A[i+1]-A[i])
for i in range(1,N+1):
    print(cost-abs(A[i+1]-A[i])-abs(A[i]-A[i-1])+abs(A[i+1]-A[i-1]))

ABC093 C - Same Integers

解答例
l=sorted(map(int,input().split()))
a=2*l[2]-l[1]-l[0]
print((a+3)//2 if a%2 else a//2)

ABC100 C - *3 or /2

解答例
n=int(input())
a=list(map(int,input().split()))
c=0
for i in a:
    while i%2==0:i,c=i/2,c+1
print(c)

ABC006 B - トリボナッチ数列

トリボナッチ数 - Wikipedia

L_0 = 0, L_1 = 0, L_2 = 1
L0=0,L1=0,L2=1
L_{n} = L_{n-1} + L_{n-2} + L_{n-3}
Ln=Ln1+Ln2+Ln3
解答例
a,b,c=0,0,1
for i in range(int(input())):
    a,b,c=b,c,a+b+c
print(a)

ABC079 B - Lucas Number

リュカ数 - Wikipedia

  • 初項(最初のリュカ数)を 2、次の項を 1 と定義し、それ以降の項は前の2つの項の和になっている数列
L_0 = 2, L_1 = 1
L0=2,L1=1
L_{n+2} = L_n + L_{n+1}
Ln+2=Ln+Ln+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])

ABC132 B - Ordinary Number

解答例
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)))

ABC135 B - 0 or 1 Swap

解答例
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")

数直線

ABC119 D - Lazy Faith

解答例
import bisect
A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
    x=int(input())
    i=bisect.bisect_right(S,x)
    j=bisect.bisect_right(T,x)
    d=INF
    for s in [S[i-1],S[i]]:
        for t in [T[j-1],T[j]]:
            d1=abs(s-x)+abs(s-t)
            d2=abs(t-x)+abs(s-t)
            d=min(d,d1,d2)
    print(d)

ABC060 C - Sentou

解答例
N,T=map(int,input().split())
t=list(map(int,input().split()))
ans=0
for i in range(N-1):
    ans+=min(t[i+1]-t[i],T)
print(ans+T)

ABC107 C - Candles

解答例
n,k=map(int,input().split())
x=sorted(list(map(int,input().split())))
print(min((min(abs(x[i])+abs(x[i+k-1]-x[i]),abs(x[i+k-1])+abs(x[i]-x[i+k-1]))) for i in range(n-k+1)))
解答例
n,k=map(int,input().split())
x=sorted(list(map(int,input().split())))
a=[]
for i in range(n-k+1):
    l=x[i]
    r=x[i+k-1]
    a.append(min(abs(l)+abs(r-l),abs(r)+abs(l-r)))
print(min(a))

ABC117 C - Streamline

解答例
N,M=map(int,input().split())
X=sorted(set(list(map(int,input().split()))))
s=[]
for i in range(M-1):
    s.append(X[i+1]-X[i])
s=sorted(s)[::-1]
print(sum(s[N-1:]))

ABC024 B - 自動ドア

解答例
n,t=map(int,input().split())
a=b=0
for i in range(n):
    s=int(input())
    if s>b:a+=s-b
    b=s+t
print(b-a)

ABC025 B - 双子とスイカ割り

解答例
n,a,b=map(int,input().split())
x=0
for i in range(n):
    s,d=input().split()
    d=int(d)
    if s=="East":
        if d<a:d=a
        if d>b:d=b
    else:
        if d<a:d=a
        if d>b:d=b
        d=-d
    x+=d
print("0" if x==0 else "East "+str(x) if x>0 else "West "+str(abs(x)))

ABC064 B - Traveling AtCoDeer Problem

解答例
input()
l=sorted(map(int,input().split()))
print(l[-1]-l[0])
解答例
input()
a=list(map(int,input().split()))
print(max(a)-min(a))

ABC070 B - Two Switches

解答例
a,b,c,d=map(int,input().split())
print(max(0,min(b,d)-max(a,c)))
解答例
a,b,c,d=map(int,input().split())
t=len(set(map(int,range(a,b+1)))&set(map(int,range(c,d+1))))-1
print("0" if t==-1 else t)

ABC093 B - Small and Large Integers

解答例
a,b,k=map(int,input().split())
r=range(a,b+1)
for i in sorted(set(r[:k])|set(r[-k:])):print(i)

ABC110 B - 1 Dimensional World's Tale

解答例
N,M,X,Y=map(int,input().split())
x=list(map(int,input().split()))+[X]
y=list(map(int,input().split()))+[Y]
print("No War" if max(x)<min(y) else "War")

ABC124 B - Great Ocean View

解答例
n=int(input())
b=c=0
for h in map(int,input().split()):
    if b<=h:
        b=h
        c+=1
print(c)

ABC130 B - Bounding

解答例
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)

ABC137 B - One Clue

解答例
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")

座標

ABC051 C - Back and Forth

解答例
sx,sy,tx,ty=map(int,input().split())
ans=[]

for i in range(ty-sy):
    ans.append("U")
for i in range(tx-sx):
    ans.append("R")
for i in range(abs(sy-ty)):
    ans.append("D")
for i in range(abs(sx-tx)):
    ans.append("L")

ans.append("L")
for i in range(ty-sy+1):
    ans.append("U")
for i in range(tx-sx+1):
    ans.append("R")
ans.append("D")
ans.append("R")
for i in range(abs(sy-ty)+1):
    ans.append("D")
for i in range(abs(sx-tx)+1):
    ans.append("L")
ans.append("U")

print("".join(ans))

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)

ABC156 C - Rally

解答例
N=int(input())
X=list(map(int,input().split()))
P=round(sum(X)/N)
print(sum((x-P)**2 for x in X))

ABC035 B - ドローン

解答例
s=input()
d=abs(s.count("L")-s.count("R"))+abs(s.count("U")-s.count("D"))
q=s.count("?")
if int(input())==1:print(d+q)
else:print(max(len(s)%2,d-q))

ABC074 B - Collecting Balls (Easy Version)

解答例
input()
k=int(input())
print(sum(min(x,k-x)*2 for x in map(int,input().split())))

ABC108 B - Ruined Square

解答例
x1,y1,x2,y2=map(int,input().split())
x=x2-x1
y=y2-y1
print(x2-y,y2+x,x1-y,y1+x)

面積

ABC062 C - Chocolate Bar

解答例
h,w=map(int,input().split())
pattern=[h//2+w//3+1,h//3+w//2+1,h,w]
if h%3==0 or w%3==0:
    pattern+=[0]
if h%2==0:
    pattern+=[h//2]
if w%2==0:
    pattern+=[w//2]
print(min(pattern))

ABC130 C - Rectangle Cutting

解答例
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)])

ABC016 A - Right Triangle

解答例
a,b,c=map(int,input().split())
print(a*b//2)

ABC039 A - 高橋直体

解答例
a,b,c=map(int,input().split())
print(2*(a*b+b*c+c*a))

ABC045 A - 台形 / Trapezoids

解答例
a,b,h=[int(input()) for i in range(3)]
print((a+b)*h//2)

ABC052 A - Two Rectangles

解答例
a,b,c,d=map(int,input().split())
print(max(a*b,c*d))

倍数

AGC028 A - Two Abbreviations

解答例
from fractions import gcd
N,M=map(int,input().split())
S=list(input())
T=list(input())
L=gcd(N,M)
print(N*M//L if all([S[i*N//L]==T[i*M//L] for i in range(L)]) else "-1")

ABC100 B - Ringo's Favorite Numbers

解答例
D,N=map(int,input().split())
l=[int(pow(100,D)*i) for i in range(1,N+1)]
print(l[N-1])

約数

  • 約数:Divisor
サンプルコード
N=100
divisor=[i for i in range(1,N+1) if N%i==0]
print(divisor)
実行結果
[1, 2, 4, 5, 10, 20, 25, 50, 100]

ABC106 B - 105

解答例
N=int(input())
count=0
for i in range(105,N+1,2):
    divisor=0
    for j in range(1,i+1):
        if(i%j==0):divisor+=1
    if(divisor==8):count+=1
print(count)

ABC120 B - K-th Common Divisor

解答例
A,B,K=map(int,input().split())
print([n for n in range(1,min(A,B)+1) if A%n==B%n==0][-K])
解答例
A,B,K=map(int,input().split())
a=[n for n in range(1,A+1) if A%n==0]
b=[n for n in range(1,B+1) if B%n==0]
print(sorted(set(a)&set(b))[::-1][K-1])

ABC118 A - B +/- A

解答例
a,b=map(int,input().split())
print(b-a if b%a>0 else a+b)

素数

  • 素数:Prime number
サンプルコード
N=101
print("Prime" if all([N%i for i in range(2,int(N**.5)+1)]) else "Not prime")
実行結果
Prime
サンプルコード
N=102
print("Prime" if all([N%i for i in range(2,int(N**.5)+1)]) else "Not prime")
実行結果
Not prime

ARC017 A - 素数、コンテスト、素数

解答例
N=int(input())
print("YES" if all([N%n for n in range(2,int(N**.5)+1)]) else "NO")
解答例
N=int(input())
print("YES" if all([N%n for n in range(2,N)]) else "NO")
解答例
N=int(input())
print("NO" if any([N%n==0 for n in range(2,N)]) else "YES")

ARC032 A - ホリドッグ

解答例
N=int(input())
S=sum(n for n in range(N+1))
flag=0
for s in range(2,S):
    if S%s==0:
        flag=1
print("WANWAN" if flag==0 and N!=1 else "BOWWOW")

ARC044 A - 素数判定

解答例
N=int(input())
flag=1
if N==1:flag=0
elif N==2 or N==3 or N==5:flag=1
elif N%2==0 or N%3==0 or N%5==0:flag=0
else:flag=1
print("Prime" if flag==1 else "Not Prime")

素因数分解

  • 素因数分解:Factoring
サンプルコード
for num in range(2,10):
    i=num
    Factoring=[]
    flag=True
    while flag:
        for j in range(2,num+1):
            if i%j==0:
                i=i/j
                if i==1:flag=False
                Factoring.append(j)
                break
    if len(Factoring)==1:print(num,"is a prime")
    else:print(num,Factoring)
実行結果
2 is a prime
3 is a prime
4 [2, 2]
5 is a prime
6 [2, 3]
7 is a prime
8 [2, 2, 2]
9 [3, 3]

約数の個数

ある整数 x が素因数分解によって x=pn×qm×...(p,q,...) と表される時、 x の約数の個数は (n+1)×(m+1)×... となる。

ABC114 D - 756

解答例
N=int(input())
e=[0]*(N+1)
for i in range(2,N+1):
    cur=i
    for j in range(2,i+1):
        while cur%j==0:
            e[j]+=1
            cur//=j
def num(m):return len(list(filter(lambda x:x>=m-1,e)))
print(num(75)+num(25)*(num(3)-1)+num(15)*(num(5)-1)+num(5)*(num(5)-1)*(num(3)-2)//2)

ABC067 C - Factors of Factorial

解答例
import math
N=math.factorial(int(input()))
i=2
ans=1
M=10**9+7
while i*i<=N:
    cnt=1
    while N%i==0:
        cnt+=1
        N//=i
    ans*=cnt
    i+=1
if N!=1:ans*=2
print(int(ans%M))

順列

  • 順列:permutation
_4 P _2 = 4 \times 3 = 12通り
4P2=4×3=12
サンプルコード
from itertools import permutations
List=["a","b","c","d"]
print(list(permutations(List,2)))
実行結果
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]
サンプルコード
from itertools import permutations
List=["a","b","c","d"]
print(len(list(permutations(List,2))))
実行結果
12
サンプルコード
from itertools import permutations
List=["a","b","c","d"]
print(list(permutations(List,2)))
実行結果
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]
サンプルコード
from itertools import permutations
List=["a","b","c","d"]
print(len(list(permutations(List,2))))
実行結果
12

ARC013 A - 梱包できるかな?

解答例
from itertools import permutations
n,m,l=map(int,input().split())
P=list(map(int,input().split()))
v=0
for p,q,r in permutations(P):
    v=max(v,(n//p)*(m//q)*(l//r))
print(v)

組み合わせ

  • 組み合わせ:combination
_4 C _2 = \frac{_4 P _2}{2!} = 6通り
4C2=4P22!=6
サンプル
from itertools import combinations
List=["a","b","c","d"]

print(list(combinations(List,2)))
# [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

print(len(list(combinations(List,2))))
# 6

ABC028 C - 数を3つ選ぶマン

解答例
from itertools import combinations
S=map(int,input().split())
print(sorted(map(sum,combinations(S,3)))[-3])

ABC089 C - March

解答例
from itertools import combinations
from collections import Counter
N=int(input())
S=Counter()
for i in range(N):
    S[input()[0]]+=1
print(sum([S[a]*S[b]*S[c] for a,b,c in combinations("MARCH",3)]))

ABC108 A - Pair

解答例
K=int(input())
print((K//2)*((K+1)//2))

経路

\frac{(width+height -2)!}{(width-1)!(height -1)!}
(width+height2)!(width1)!(height1)!

ABC034 C - 経路

解答例
from math import factorial
W,H=map(int,input().split())
m=10**9+7
print(factorial(W+H-2)*pow(factorial(H-1)*factorial(W-1)%m,m-2,m)%m)

色塗り

ABC046 B - AtCoDeerくんとボール色塗り / Painting Balls with AtCoDeer

解答例
n,k=map(int,input().split())
print(k*(k-1)**(n-1))

重複組み合わせ

サンプルコード
from itertools import combinations_with_replacement
List=["a","b","c","d"]
print(list(combinations_with_replacement(List,3)))
実行結果
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'a', 'd'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'c'), ('a', 'c', 'd'), ('a', 'd', 'd'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'b', 'd'), ('b', 'c', 'c'), ('b', 'c', 'd'), ('b', 'd', 'd'), ('c', 'c', 'c'), ('c', 'c', 'd'), ('c', 'd', 'd'), ('d', 'd', 'd')]
サンプルコード
from itertools import combinations_with_replacement
List=["a","b","c","d"]
print(len(list(combinations_with_replacement(List,3))))
実行結果
20

ABC011 D - 大ジャンプ
ABC021 D - 多重ループ

直積

サンプルコード
from itertools import product
A=["a","b","c"]
X=["x","y","z"]
for p in product(A,X):
    print(p)
実行結果
('a', 'x')
('a', 'y')
('a', 'z')
('b', 'x')
('b', 'y')
('b', 'z')
('c', 'x')
('c', 'y')
('c', 'z')
サンプルコード
from itertools import product
A=["a","b","c"]
X=["x","y","z"]
for a,x in product(A,X):
    print(a,x)
実行結果
a x
a y
a z
b x
b y
b z
c x
c y
c z
サンプルコード
from itertools import product
for p in product("357",repeat=3):
    print("".join(p))
実行結果
333
335
337
353
355
357
373
375
377
533
535
537
553
555
557
573
575
577
733
735
737
753
755
757
773
775
777

確率

  • 未分類

ABC024 D - 動的計画法
ABC028 D - 乱数生成

期待値

ABC078 C - HSI

解答例
n,m=map(int,input().split())
print((1900*m+100*(n-m))*2**m)

ABC003 A - AtCoder社の給料

解答例
print((int(input())+1)*5e3)

数列の和

f(x) = \sum_{1}^n x = \frac{n(n + 1)}{2}
f(x)=n1x=n(n+1)2
サンプルコード
n=10
print(n*(n+1)//2)
実行結果
55
サンプルコード
n=10
print(sum(range(n+1)))
実行結果
55

ABC099 B - Stone Monument

解答例
a,b=map(int,input().split())
n=b-a
print(n*(n+1)//2-b)

ABC043 A - キャンディーとN人の子供イージー / Children and Candies (ABC Edit)

解答例
n=int(input())
print(n*(n+1)//2)

連立方程式の解

2x+3y+4z=10 (0≦x<20, 0≦y<30, 0≦z<40)
2x+3y+4z=10 0x<20,0y<30,0z<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)
2x+3y+4z=10 0x<20,0y<30,0z<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)
2x+3y+4z=10 0x<20,0y<30,0z<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)
x+y+z=S 0x,y,z<k25000S<3K
サンプルコード
s=7000
k=2500
print(len([1 for y in range(k) for x in range(k) if 0<=s-x-y<=k]))
実行結果
124750
サンプルコード
s=7000
k=2500
print([1 for y in range(k) for x in range(k) if 0<=s-x-y<=k].count(1))
実行結果
124750

ABC087 B - Coins

解答例
a,b,c,x=[int(input()) for _ in range(4)]
print([500*x+100*y+50*z for z in range(c+1) for y in range(b+1) for x in range(a+1)].count(x))
解答例
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)

ABC105 B - Cakes and Donuts

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

平方根の整数部と小数部の算出

y = x^{1/2} (a:整数部, b:小数部)
y=x1/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

ABC077 B - Around Square

解答例
print(int(int(input())**.5)**2)

相加相乗平均

\frac{a+b}{2} ≧ \sqrt{ab}
a+b2ab

ABC026 A - 掛け算の最大値

解答例
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}
distance(x,y)=ni=1(xiyi)2
\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}
(x1x2)2+(y1y2)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)

ABC145 C - Average Length

解答例
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)

ABC133 B - Good Distance

解答例
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|
distance(x,y)=ni=1|xiyi|
|x_1 - x_2| + |y_1 - y_2|
|x1x2|+|y1y2|

ABC057 B - Checkpoints

解答例
n,m=map(int,input().split())
ab=[[int(j) for j in input().split()] for i in range(n)]
cd=[[int(j) for j in input().split()] for i in range(m)]
for a,b in ab:
    l=[abs(a-c)+abs(b-d) for c,d in cd]
    print(l.index(min(l))+1)
解答例
n,m=map(int,input().split())
a=[[int(j) for j in input().split()] for i in range(n)]
c=[[int(j) for j in input().split()] for i in range(m)]
for i in range(n):
    d=10e8
    b=0
    for j in range(m):
        if abs(a[i][0]-c[j][0])+abs(a[i][1]-c[j][1])<d:
            d=abs(a[i][0]-c[j][0])+abs(a[i][1]-c[j][1])
            b=j+1
    print(b)

ヘロンの公式

S = \sqrt{s(s-a)(s-b)(s-c)} \\
s = \frac{a+b+c}{2}
S=s(sa)(sb)(sc)s=a+b+c2

ヘロンの公式 - 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.
f(n)={n/2(ifn=0)3n+1(ifn=1)

コラッツの問題 - 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
PQ
解答例
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}
(123456789)(111)=(61524)
サンプルコード
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}
(123456789)T(111)=(121518)
サンプルコード
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=(123456789)
A^T =
\begin{pmatrix}
1 & 4 & 7 \\
2 & 5 & 8 \\
3 & 6 & 9 \\
\end{pmatrix}
AT=(147258369)
サンプルコード
Matrix=[[1,2,3],[4,5,6],[7,8,9]]
for Row in zip(*Matrix):print(Row)
実行結果
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)

ABC107 B - Grid Compression

解答例
h,w=map(int,input().split())
a=[[j for j in input()] for i in range(h)]
b=[x for x in a if "#" in x]
c=zip(*[y for y in zip(*b) if "#" in y])
for d in c:print("".join(d))

行列の回転

A =
\begin{pmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{pmatrix}
A=(123456789)
A^{行列の回転} =
\begin{pmatrix}
3 & 6 & 9 \\
2 & 5 & 8 \\
1 & 4 & 7 \\
\end{pmatrix}
A=(369258147)

ABC004 B - 回転

解答例
print("\n".join(input() for _ in range(4))[::-1])
解答例
for i in reversed([input() for i in range(4)]):
    print(i[::-1])

ABC036 B - 回転

解答例
s=[input() for i in range(int(input()))]
for x in zip(*s):print("".join(x)[::-1])
解答例
s=reversed([input() for i in range(int(input()))])
for x in zip(*s):print("".join(x))

第11章 カテゴリ観点

桁数

ABC136 B - Uneven Numbers

解答例
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)))

グリッド

ABC096 C - Grid Repainting 2

解答例
H,W=map(int,input().split())
S=["."+input()+"." for i in range(H)]
S=["."*(W+2)]+S+["."*(W+2)]
flag=0
for i in range(H):
    for j in range(W):
        if S[i][j]=="#":
            if S[i-1][j]=="." and S[i+1][j]=="." and S[i][j-1]=="." and S[i][j+1]==".":
                flag=1
print("Yes" if flag==0 else "No")

ABC049 B - たてなが / Thin

解答例
h,w=map(int,input().split())
for i in range(h):
    s=input()
    print(s+"\n"+s)

ABC054 B - Template Matching

解答例
N,M=map(int,input().split())
A=[input() for 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")

ABC062 B - Picture Frame

解答例
h,w=map(int,input().split())
print("#"*(w+2))
for i in range(h):print("#"+input()+"#")
print("#"*(w+2))

ABC075 B - Minesweeper

解答例
h,w=map(int,input().split())
s=[input() for _ in range(h)]
for i in range(h):
    l=""
    for j in range(w):
        if s[i][j]=="#":
            l+="#"
        else:
            l+=str(sum([t[max(0,j-1):min(w,j+2)].count("#") for t in s[max(0,i-1):min(h,i+2)]]))
    print(l)

ABC107 B - Grid Compression

解答例
h,w=map(int,input().split())
a=[[j for j in input()] for i in range(h)]
b=[x for x in a if "#" in x]
c=zip(*[y for y in zip(*b) if "#" in y])
for d in c:print("".join(d))

再帰

ABC115 D - Christmas

解答例
N,X=map(int,input().split())
a,p=[1],[1]
for i in range(N):
    a.append(a[i]*2+3)
    p.append(p[i]*2+1)
def f(n,x):
    if n==0:return 0 if x<=0 else 1
    elif x<=1+a[n-1]:return f(n-1,x-1)
    else:return p[n-1]+1+f(n-1,x-2-a[n-1])
print(f(N,X))

日時

ARC023 A - 経過日数

解答例
import datetime
y=int(input())
m=int(input())
d=int(input())
print((datetime.date(2014,5,17)-datetime.date(y,m,d)).days)
解答例
Y=int(input())
M=int(input())
D=int(input())
if M==1 or M==2:
    Y-=1
    M+=12
print(735369-(365*Y+Y//4-Y//100+Y//400+306*(M+1)//10+D-429))

ABC012 B - 入浴時間

解答例
n=int(input())
print("%02d:%02d:%02d"%(n//3600,(n%3600)//60,n%60))

ABC096 A - Day of Takahashi

解答例
a,b=map(int,input().split())
print(a-1 if a>b else a)

ABC119 A - Still TBD

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

時計

ABC030 B - 時計盤

解答例
n,m=map(int,input().split())
a=abs(n%12*30-5.5*m)
print(min(a,360-a))

コイン

ARC041 A - コインの反転

解答例
x,y=map(int,input().split())
k=int(input())
print(x+y-abs(k-y))

オセロ

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)

宝くじ

ARC006 A - 宝くじ

解答例
E=set(input().split())
b=input()
L=set(input().split())
l=len(E&L)
ans=0
if l==5 and b in L:ans=2
elif l==6:ans=1
elif l>2:ans=8-l
else:ans=0
print(ans)
解答例
a = [int(i) for i in input().split()]
b = int(input())
c = [int(i) for i in input().split()]
k = 6 - len(set(a) - set(c))
if k == 5 and b in c: print(2)
else: print({6:1,5:3,4:4,3:5}.get(k,0))

ビンゴ

ABC157 B - Bingo

解答例
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")

ゾロ目

ARC046 A - ゾロ目数

解答例
N=int(input())-1
print(str(N%9+1)*(N//9+1))
解答例
N=int(input())
num=1
while N>0:
    if len(set(str(num)))==1:N-=1
    num+=1
print(num-1)

N値判定

  • 2値判定(Zero/NotZero判定)
f(x) = \left\{
\begin{array}{ll}
Zero & (x=0) \\
Not Zero & (x\neq0)
\end{array}
\right.
f(x)={Zero(x=0)NotZero(x0)
サンプルコード
x=int(input())
print(["Not Zero","Zero"][x==0])
x 0 1
x==0 True False
["Not Zero","Zero"][x==0] Zero Not Zero

ABC056 A - HonestOrDishonest

解答例
print("HD"[len(set(input()))%2])

ABC099 A - ABD

解答例
print(["ABC","ABD"][len(input())>3])

ABC102 A - Multiple of 2 and N

解答例
n=int(input())
print([N,N*2][N%2])
  • 2値判定(奇数/偶数判定、入力数1)
f(x) = \left\{
\begin{array}{ll}
Even & (x\;\;mod\;\;2\;\;=\;\;0) \\
Odd & (x\;\;mod\;\;2\;\;=\;\;1)
\end{array}
\right.
f(x)={Even(xmod2=0)Odd(xmod2=1)
サンプルコード
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.
f(x,y)={Even(xymod2=0)Odd(xymod2=1)
サンプルコード
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.
f(x)={Even(ifximod2=0)Odd(otherwise)
サンプルコード
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.
f(x)={Positive(x>0)0(x=0)Negative(x<0)
サンプルコード
x=int(input())
print(["0","Positive","Negative"][x>0 or -(x<0)])
x -1 0 1
x>0 False False True
x<0 True False Flase
-(x<0) -1 0 0
x>0 or -(x<0) -1 0 True
["0","Positive","Negative"][x>0 or -(x<0)] Negative 0 Positive

ABC078 A - HEX

解答例
x,y=input().split()
print("=><"[x>y or -(x<y)])

ABC083 A - Libra

解答例
A,B,C,D=map(int,input().split())
print(["Balanced","Left","Right"][(A+B>C+D)-(A+B<C+D)])

ABC104 A - Rated for Me

解答例
print(["ABC","ARC","AGC"][(int(input())+400)//1600])

Lambda式

ABC045 A - 台形 / Trapezoids

解答例
x=lambda:int(input())
print((x()+x())*x()//2)

ABC054 A - One Card Poker

解答例
a,b=map(lambda x:(int(x)+13)%15,input().split())
print("Alice" if a>b else "Bob" if a<b else "Draw")

ABC087 A - Buying Sweets

解答例
i=lambda:int(input())
print((i()-i())%i())

ABC092 A - Traveling Budget

解答例
f=lambda:min(int(input()),int(input()))
print(f()+f())

参考

本記事は下記を参考にしました。

ドキュメント

書籍

Python関連ページ

競技プログラミング関連ページ

AtCoder関連サービス

AtCoder関連情報

Pythonコーディング規約

Markdown記法

ユーザー登録して、Qiitaをもっと便利に使ってみませんか。
  1. あなたにマッチした記事をお届けします
    ユーザーやタグをフォローすることで、あなたが興味を持つ技術分野の情報をまとめてキャッチアップできます
  2. 便利な情報をあとで効率的に読み返せます
    気に入った記事を「ストック」することで、あとからすぐに検索できます
コメント
この記事にコメントはありません。
あなたもコメントしてみませんか :)
すでにアカウントを持っている方は
ユーザーは見つかりませんでした