Problem 546067 · hard · Phase 05 Advanced Algorithms & Graphs

Keeping Rivals Apart at the Scrimmage

BFS · bipartite graphs · connected components · subset-sum DP

n players 0 .. n-1 must be split into two teams for a scrimmage; every player joins exactly one team, and a team may be empty. Each pair [u, v] in rivals says players u and v refuse to be on the same team (a pair may be listed more than once).

Return the smallest possible value of |size of team 1 - size of team 2| over all splits that keep every rival pair apart, or -1 if no such split exists.

Examples

Input:  n = 5, rivals = [[0, 1], [1, 2], [3, 4]]
Output: 1
Explanation: {0, 2, 3} against {1, 4}.

Input:  n = 3, rivals = [[0, 1], [1, 2], [2, 0]]
Output: -1
Explanation: three mutual rivals cannot fit on two teams.

Input:  n = 6, rivals = [[0, 1], [0, 2], [0, 3]]
Output: 0
Explanation: {0, 4, 5} against {1, 2, 3}.

Constraints

  • 1 <= n <= 2000, 0 <= len(rivals) <= 10**4, u != v.

Goals

  • Two-colour each component and detect an odd cycle
  • See that each component can only be flipped as a whole
  • Turn the balancing choice into a subset-sum dynamic programme
Starting Python…