How Many to Be Happy?
InterviewTime limit0.5sMemory limit512 MB
For each edge find the fewest edges to delete so that it lies in some minimum spanning tree, then sum those counts.
- Level
Medium7 of 10
- Topics
- Minimum spanning tree, Graph, Union-find, Greedy
- Solved
- No attempts yet
Problem
Let be a connected simple undirected graph in which every edge has a weight. Recall the minimum spanning tree (MST) problem. For each edge of , we ask how much must be modified before belongs to an MST of . Some MST of may already contain . In that case we say that is happy in , and we define . It may also happen that no MST of contains . In that case we say that is unhappy in . We may then delete some edges of to obtain a connected graph in which is happy. is the minimum number of edges to delete from so that is happy in the resulting graph .

Figure E.1. A complete graph with 3 nodes.
The graph in Figure E.1 has 3 nodes and 3 edges. Its MST consists of the two edges with weights 1 and 2, so those two edges are happy in the graph. To make the edge of weight 3 happy, delete either one of the two happy edges.
Given a connected simple undirected graph , compute for every edge of and print the total sum.
Input
The first line contains two positive integers and , the number of vertices and the number of edges of the graph, where and . The vertices are numbered from 1 to .
Each of the next lines contains three positive integers , , and , describing an edge between vertex and vertex with weight . Every weight is an integer between 1 and 500, inclusive.
The graph is connected, it has no self loop, and no two edges join the same pair of vertices.
Output
Print one integer , the sum of over all edges of .