Graph Theory37 sections · 1633 units
Open in Course

CSES 1668 Building Teams - Implementation

The code

Here is the full solution:

function buildTeams():
    read n, m
    graph := array of n + 1 empty lists
    for i from 1 to m:
        read a, b
        graph[a].append(b)
        graph[b].append(a)
        color := array of size n + 1, all 0
        for i from 1 to n:
            if color[i] = 0 then
                if not bfs(i, 1, graph, color) then
                    print "IMPOSSIBLE"
                    return
    for i from 1 to n:
        print color[i]

The BFS function is the same as before: color nodes, check conflicts. On success, output each color plus one.

This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.