This problem ask you whether it is possible to generate the MST by moving some edges away. If so, print the number of redundant edges, if not print forest.
A modified Kruskal Algorithm: We implement a find_root function that recursively trace back to the root of a node, and if two edges share the same root, we push that into our answer
array.
And the size of our answer
is the final result.
This problem is equivalent to finding a shortest path between in a similarly constructed graph with a starting point and a target. So a simple Dijkstra algorithm can solve this problem.
The problem is about checking reachability from a character to another. Since the constraints are small, simply doing dfs each time for a character will do the job.
Bonus Question: What if the alphabet size is some and the length of each of the () is some ?
To be Presented by Zeyuan.
The naive way is to each time delete a different edge and see if the graph is acyclic, which will cost time.
A key observation is that by finding a specfic cycle, to make the graph acyclic, we must delete an edge that is on that cycle. Since the number of edges on a cycle is at most , then the overall complexity will be improved to be .
To be Presented by Leo Liu.