公式

A - Who Ate the Cake? 解説 by toam


初心者の方へ

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

投稿日時:
最終更新: