Official

D - Swap Hats Editorial by en_translator


By replacing B\(1\) , G\(2\) , R\(3\), we will explain it as a problem on permutations of \((1, 2, 3)\).

There are six permutations of \((1, 2, 3)\):

  • \((1, 2, 3)\)
  • \((1, 3, 2)\)
  • \((2, 1, 3)\)
  • \((2, 3, 1)\)
  • \((3, 1, 2)\)
  • \((3, 2, 1)\).

Here is a diagram that illustrates the possible transitions in one operation:

As you can see, the permutations can be divided into two groups:

  • Group A : \((1, 2, 3), (2, 3, 1), (3, 1, 2)\)
  • Group B : \((1, 3, 2), (2, 1, 3), (3, 2, 1)\)

In one operation, we can transform an element of Group A to an element of Group B, and an element of Group B to an element of Group A, so in order to determine if \(S\) can be transformed to \(T\) with \(10^{18}\), it is sufficient to check if \(S\) and \(T\) belongs to the same group.

Generalization

What if the number of elements are not \(3\), but \(n\)? Here is where the idea of inversion number works.

The inversion number is defined for a permutation \((A_1, A_2, \dots, A_n)\) of \((1, 2, \dots, n)\) by the number of pairs of integers \((i, j)\) such that \(i < j\) and \(A_i > A_j\). A permutation having an even inversion number is called an even permutation, and that of having an odd inversion number is called an odd permutation. An even permutation always turns into an odd permutation in one operation, and an odd permutation always turns into an even permutation in one operation, so no matter how large even number of times the operation is performed, it cannot be moved to the different group.

The technique of odd/even permutations is frequently used in ARC and other contest, so we think it is worth learning.

Sample code (C++)

#include <iostream>
#include <string>
using namespace std;

bool sign(string S){
    return S == "R G B" || S == "G B R" || S == "B R G";
}
int main(){
    string S, T;
    getline(cin, S);
    getline(cin, T);
    if(sign(S) == sign(T)) cout << "Yes" << endl;
    else cout << "No" << endl;
}

Sample code (Python)

A = ["R G B", "G B R", "B R G"]

S = input()
T = input()
print("Yes" if (S in A) == (T in A) else "No")

posted:
last update: