import java.util.*; /** * Process all edges in increasing order of weight. If the edge is not in the * tree, then check if swapping the edge into the tree will result in a lower * cost spanning tree if we substitute it for the largest weight edge that is * in the cycle that would be created by adding the current edge into the tree. * Repeat until all edges are processed. Find the largest weight edge each time * by using a breadth first search in the tree. * * @author Finn Lidbetter */ public class broken_mst_easy_finn { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); Edge[] edges = new Edge[m]; Edge[] sortedEdges = new Edge[m]; Node[] nodes = new Node[n]; for (int i=0; i swapOuts = new ArrayList<>(); ArrayList swapIns = new ArrayList<>(); for (Edge e: sortedEdges) { if (!inTree[e.id]) { int candidateId = maxWeightEdgeId(e.u, e.v, nodes, edges, inTree); if (edges[candidateId].w > e.w) { swapOuts.add(edges[e.id]); swapIns.add(edges[candidateId]); inTree[candidateId] = false; inTree[e.id] = true; } } } System.out.println(swapIns.size()); for (int i=0; i q = new LinkedList<>(); q.offer(src); vis[src] = true; while (q.size() > 0) { int nodeId = q.poll(); if (nodeId==dest) { break; } for (int edgeId: nodes[nodeId].adj) { if (!inTree[edgeId]) { continue; } Edge edge = edges[edgeId]; int other = (nodeId == edge.u) ? edge.v : edge.u; if (!vis[other]) { vis[other] = true; prevEdge[other] = edge.id; q.offer(other); } } } int curr = dest; int maxWeight = -1; int maxWeightEdgeId = -1; while (curr != src) { int edgeId = prevEdge[curr]; Edge edge = edges[edgeId]; int prev = (curr == edge.u) ? edge.v : edge.u; if (edge.w > maxWeight) { maxWeight = edge.w; maxWeightEdgeId = edge.id; } curr = prev; } return maxWeightEdgeId; } } class Node { int id; ArrayList adj; public Node(int idd) { id = idd; adj = new ArrayList<>(); } } class Edge implements Comparable { int id; int u,v,w; public Edge(int idd, int uu, int vv, int ww) { id = idd; u = uu; v = vv; w = ww; } public int compareTo(Edge e2) { if (w==e2.w) { return id - e2.id; } return w - e2.w; } }