Official
A - Who Ate the Cake? Editorial
by
A - Who Ate the Cake? Editorial
by
toam
初心者の方へ
- プログラミングの学習を始めたばかりで何から手をつけるべきかわからない方は、まずは practice contest の問題A「Welcome to AtCoder」をお試しください。言語ごとに解答例が掲載されています。
- また、プログラミングコンテストの問題に慣れていない方は、 AtCoder Beginners Selection の問題をいくつか試すことをおすすめします。
- C++入門 AtCoder Programming Guide for beginners (APG4b) は、競技プログラミングのための C++ 入門用コンテンツです。
- Python入門 AtCoder Programming Guide for beginners (APG4bPython) は、競技プログラミングのための Python 入門用コンテンツです。
\(A=B\) のときは,人 \(A\) 以外の残りの二人のうちどちらが犯人かを特定できないため答えは -1
になります.
\(A\neq B\) のときは,\(1,2,3\) のうち \(A,B\) 以外のものを出力すればよいです.\(A\neq B\) である入力は \(3\times 2=6\) 通りあるため,\(6\) 通りの場合分けをすることでこの問題を解くことができます.
A, B = map(int, input().split())
if A == B:
print(-1)
if A == 1 and B == 2:
print(3)
if A == 1 and B == 3:
print(2)
if A == 2 and B == 1:
print(3)
if A == 2 and B == 3:
print(1)
if A == 3 and B == 1:
print(2)
if A == 3 and B == 2:
print(1)
また,犯人を \(C\) としたとき,\(A,B,C\) には以下の性質を満たすことを利用すると場合分けを減らすことができます.
- \(C=6-A-B\)
- \(C=A\oplus B\) (\(\oplus\) は排他的論理和)
A, B = map(int, input().split())
if A == B:
print(-1)
else:
print(6 - A - B)
A, B = map(int, input().split())
if A == B:
print(-1)
else:
print(A ^ B)
ほかにも,言語の機能をうまく利用することで場合分けを減らすことができます.
A, B = map(int, input().split())
S = set([1, 2, 3])
S.discard(A) # S に A が含まれていたら A を削除する,含まれなければ何もしない
S.discard(B) # S に B が含まれていたら B を削除する,含まれなければ何もしない
if len(S) == 1:
print(S.pop())
else:
print(-1)
posted:
last update: