Problem Description
Given an undirected graph with n nodes and edges of three types (Alice-only, Bob-only, and common to both), remove the maximum number of redundant edges while ensuring that both Alice and Bob can traverse the entire graph (i.e. the graph remains connected for both users). If it’s impossible for both to traverse the entire graph, return -1.
Key Insights
- Use the union-find (disjoint set union) data structure to efficiently manage connectivity.
- Process type 3 (common) edges first since they benefit both Alice and Bob.
- Then process type 1 (Alice-only) edges for Alice’s connectivity and type 2 (Bob-only) edges for Bob’s connectivity.
- Count the edges that are actually used and subtract them from the total to get the maximum removals.
- Finally, verify that both Alice’s and Bob’s graphs are fully connected.
Space and Time Complexity
Time Complexity: O(E * α(N)) where α is the inverse Ackermann function (almost constant) Space Complexity: O(N) for maintaining the union-find data structures
Solution
We approach the problem using two separate union-find structures – one for Alice and one for Bob. First, we process type 3 edges (usable by both) and union the nodes in both DSUs. Next, we process type 1 edges for Alice’s DSU and type 2 edges for Bob’s DSU. An edge that does not contribute to union (i.e. both nodes already connected) is redundant and can be removed. After processing all edges, we check if both DSUs have a single connected component. If yes, the total number of removable edges is (total edges - used edges); otherwise, return -1. The key idea is to maximize the sharing of edges between Alice and Bob by using the shared edges first.