Given two spanning trees on the same N stations, output a shortest sequence of weekend swaps, each removing one tree edge and adding another, so every intermediate graph stays a spanning tree and the target tree is reached.
Hard8GraphTreeGreedyUnion-findNo attempts yetTime limit2sMemory limit1024 MBThe Stockholm subway operates inefficiently. The city looks different from when the current lines were built, so some sections are heavily overused while other lines are barely used.
The city council has decided to rebuild the subway. The current system consists of N stations, with N−1 pairs of stations connected by tracks so that it is possible to travel between any pair of stations by subway. The council has made a new plan that uses the same N stations but another set of N−1 tracks that still connects all stations.
To minimize disruption in the busy subway, reconstruction must proceed one track at a time. Every weekend, exactly one track is closed and one new track is built. Hence there are always N−1 tracks. Moreover, after the work of each weekend, it must still be possible to travel between any pair of stations.
Find a way to construct the new subway network so that these conditions hold. The plan must use as few weekends as possible.
The first line contains an integer N. N is at least 1. The next N−1 lines describe the tracks in the current subway system. Each track is described by two space-separated integers a b, the numbers of the stations the track connects. Station numbers run from 0 to N−1 and are zero-indexed. It is possible to travel between any pair of stations using these tracks.
The next N−1 lines describe the tracks that must belong to the new subway system, in the same format. If N is 1, there are no track lines.
First, output the number of weekends K required by the construction plan. Then output K lines, one for each weekend in chronological order. Each line must contain four integers a1 b1 a2 b2, meaning that the track connecting a1 and b1 is closed and a track connecting a2 and b2 is built.
After each weekend there must be exactly N−1 tracks and all stations must stay connected, and after the last weekend the network must equal the target network. Among all plans satisfying the conditions, output one with the smallest possible number of weekends.