Explanation
Given the number of colored and uncolored nodes, the maximum number of edges that can exist is where represents the number of colored nodes, and represents the number of uncolored nodes.
This is because an edge can be drawn from each colored node to every other uncolored node. However, we already have edges, so the answer is .
To find the number of colored and uncolored nodes, we can run a DFS, incrementing the number of colored and uncolored nodes as we traverse the graph.
Implementation
Time Complexity:
C++
#include <iostream>#include <vector>using namespace std;const int MAX_N = 100000;// +1 for 1-indexed nodesvector<int> adj[MAX_N + 1];// counters for colored and uncolored nodes
Java
import java.io.*;import java.util.*;public class Bipartiteness {public static ArrayList<Integer>[] adj;// counters for colored and uncolored nodespublic static long[] count = {0, 0};public static void main(String[] args) throws IOException {
Python
# counters for colored and uncolored nodesc = 0uc = 0def dfs(node: int, parent: int, col: bool) -> int:global c, uc"""Iteratively DFS with a stack.While we can increase the recursion depth with sys.setrecursionlimit,
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!