Explanation
The key idea is to focus on the connected components of both graphs. Any edge in that connects vertices from different components in is problematic because it creates a connection that doesn't exist in . These edges are "invalid" and must be removed. Counting these invalid edges gives us the first part of the solution: the number of edges we need to remove from .
After removing these invalid edges, might end up with more connected components than . To fix this, we need to add edges to to merge these extra components until the number of connected components in matches that in . Each additional component in requires one edge addition to merge it with another component.
Finally, we calculate the minimum number of operations by adding these two values:
- The number of invalid edges that need to be removed
- The number of extra connected components in that need to be merged
Implementation
Time Complexity:
C++
#include <functional>#include <iostream>#include <map>#include <vector>using std::cout;using std::function;using std::pair;using std::vector;
DSU Implementation
Time Complexity:
C++
#include <array>#include <iostream>#include <numeric>#include <vector>using std::array;using std::cout;using std::vector;/**
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!