Graph Theory37 sections · 1633 units
Open in Course

CSES 1668 Building Teams - Algorithm

Step by step

Here is the complete algorithm:

1.1. Read nn, mm. Build adjacency list from mm edges.

2.2. Create color array of size n+1n+1, all 1-1.

3.3. For each pupil ii from 11 to nn: if color[i] == -1, run BFS, coloring with 00 and 11. If conflict found, print "IMPOSSIBLE" and exit.

4.4. If no conflicts, print color[1]+1, color[2]+1, ..., color[n]+1. That is it. The algorithm you already know produces the output directly. This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.