Official Analysis (C++)

Explanation

The key idea is to focus on the connected components of both graphs. Any edge in FF that connects vertices from different components in GG is problematic because it creates a connection that doesn't exist in GG. 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 FF.

After removing these invalid edges, FF might end up with more connected components than GG. To fix this, we need to add edges to FF to merge these extra components until the number of connected components in FF matches that in GG. Each additional component in FF 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 FF that need to be merged

Implementation

Time Complexity: O(N+Mlog(M)) \mathcal{O}(N + M \log(M))

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: O(N+M)\mathcal{O}(N + M)

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!