#P4381. [IOI 2008] Island
[IOI 2008] Island
Description
You plan to tour a park that consists of islands. From each island , the local authority has built a bridge to another island, with length , and bridges can be walked in both directions. In addition, for every pair of islands there is a dedicated ferry that connects the two. Compared with taking a ferry, you prefer walking. You want the total length of bridges you walk across to be as large as possible, subject to the following rules:
- You may choose any island to start your tour.
- No island may be visited more than once.
- At any time, you may move from your current island to another unvisited island . You may do so in one of the following ways:
- Walk: only if there is a bridge directly between the two islands. In this case, the bridge length is added to your total walking distance.
- Ferry: you may choose this only if there is no combination of bridges and ferries you have already used that allows you to get from to . When checking reachability, you should consider all paths, including those that pass through islands you have already visited.
Note that you do not have to visit all the islands, and you might be unable to walk across all the bridges.
Write a program that, given bridges and their lengths, computes the maximum possible sum of bridge lengths you can walk under the rules above.
Input Format
The first line contains an integer , the number of islands in the park.
Each of the next lines describes one island. The -th line contains two integers, separated by a single space, describing the bridge built from island : the first integer is the other endpoint island, and the second integer is the bridge length . You may assume that the endpoints of every bridge are always different islands.
Output Format
Output a single integer, the maximum possible walking distance.
7
3 8
7 2
4 2
1 4
1 9
3 4
2 3
24
Hint
Sample explanation:
In the sample, bridges are , , , , , , and . Note that there are two different bridges between islands and .
One way to achieve the maximum walking distance is as follows:
- Start at island .
- Walk across the bridge of length to island .
- Walk across the bridge of length to island .
- Walk across the bridge of length to island .
- Take the ferry from island to island .
- Walk across the bridge of length to island .
You end at island , and your total walking distance is .
Only island is not visited. Note that, at the end of the tour above, you cannot visit that island. More precisely:
- You cannot walk there because there is no bridge between island (your current island) and island .
- You cannot take a ferry there because island is reachable from your current island . One possible way is: take bridge , then the previously used ferry from island to island , then take bridge , and finally bridge .
Constraints: For of the testdata, , .
Translated by ChatGPT 5
京公网安备 11011102002149号