Road Trip
InterviewTime limit1sMemory limit128 MB
Given a weighted tree rooted at city 1, remove exactly one non-root vertex so the round trip from city 1 covering all remaining cities is shortest, and report that length.
- Level
Medium5 of 10
- Topics
- Tree, DFS, Graph, Implementation
- Solved
- No attempts yet
Problem
A traveling band wants to play a show in every major city in their state and then return to the city they started from. After looking at the cost of renting a venue in each city, they realize their tight budget lets them skip playing in exactly one city.
The band has already chosen which roads to use, and the chosen roads contain no cycles while still connecting every city — that is, the chosen roads form a tree. Each road is two-way and may be driven any number of times.
The band always starts and finishes at city 1, so they can never skip city 1. When they skip a city, that city and the roads touching it are removed, and every remaining city must still be reachable over the chosen roads. Among all cities they are allowed to skip, they pick the one that makes their round trip as short as possible.
Output the length of that shortest possible round trip.
Input
The first line contains the number of data sets. The data sets follow, each in the form described below.
The first line of a data set contains two integers and , the number of cities and the number of roads, where and .
Each of the next lines describes one two-way road with three integers , , , meaning there is a road of length between city and city (). The roads contain no cycles, so they form a tree that connects all cities. The band always starts at city 1.
Output
For each data set, print a line of the form Data Set x:, where is the number of the data set (starting from 1). On the next line, print the minimum distance the band travels when it skips the best single city, visits every remaining city, and returns to city 1. Print one blank line after each data set.