Hats problem

Question

Hints

Answer