Official

A - Who Ate the Cake? Editorial by en_translator


For beginners

If \(A=B\), then we cannot determine which of the other two is the culprit, so the answer is -1.

If \(A\neq B\), it is sufficient to print the one of \(1,2,3\) that is not \(A\) nor \(B\). There are \(3\times 2=6\) possible inputs that satisfy \(A\neq B\), so one can solve the problem by checking six conditions.

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)

Also, if we denote the culprit by \(C\), then one can use the following properties of \(A,B,C\) to reduce the conditional branch.

  • \(C=6-A-B\)
  • \(C=A\oplus B\) (\(\oplus\) is the exclusive logical sum)
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)

Also, one can use a language feature to reduce conditional branch.

A, B = map(int, input().split())
S = set([1, 2, 3])
S.discard(A) # Remove A from S if present, or do nothing if absent
S.discard(B) # Remove B from S if present, or do nothing if absent

if len(S) == 1:
    print(S.pop())
else:
    print(-1)

posted:
last update: