progress

~/problems / Graphs / Bipartite graphs / 2-colouring

Most edges you can add to a tree and stay bipartite

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

You get a tree on nodes 1 .. n as n - 1 undirected edges. Add as many new edges as possible so the graph stays bipartite and simple (no self-loops, no duplicate edges).

Write max_edges_to_add(n, edges) -> int.

max_edges_to_add(3, [(1, 2), (1, 3)])           # 0   (2 and 3 are on the same side)
max_edges_to_add(5, [(1, 2), (2, 3), (3, 4), (4, 5)])
# 2   (1-4 and 2-5)

n goes up to 100,000; the answer can exceed 2^31 (use 64-bit integers in C++ or Java).

⭐ Bonus: a speed test on a 100,000-node path earns a star if you count the two sides without deep recursion.

Show hint

A tree splits into two sides in only one way, and added edges can't change that. Count which pairs are still allowed.

Topic: Bipartite graphs / 2-colouring. BFS/DFS colouring; an odd cycle means not bipartite.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc