Skip to main content
1 of 3
Pranay
  • 23.9k
  • 1
  • 50
  • 151

Here’s an algorithmic way to do this.

We can associate a directed graph by assigning a vertex to each person and placing a directed edge from i to j if i has a grudge against j. So each vertex has exactly one outgoing edge.

Pick a vertex v0 and consider it to be level 0. Place any vertex that has grudge against v0 in level 1. And so on. This way, there is no edge within a level. In particular, a vertex at level k has a grudge against some vertex at level k-1, except for v0, which has a grudge against exactly one vertex in some level l below. If l is odd, we can colour the vertices with two colours, alternating every level. Else, use two colours up to level l-1, then use a third colour at level l, and then continue using the first two colours from level l+1 and above.

If there are any leftover vertices, repeat the same algorithm as above for their connected components.

Pranay
  • 23.9k
  • 1
  • 50
  • 151