#graph402. Island
Island
Island
Problem Source
IOI 2008
Problem Description
You are going to tour a park consisting of islands. The local administration has built from each island a bridge of length to another island, though the bridge can be walked in both directions. In addition, for every pair of islands there is a dedicated ferry running between the two. Compared to taking a ferry, you prefer walking. You want the total length of bridges you walk to be as large as possible, subject to the following restrictions:
- You may freely choose an island to start the tour.
- No island may be visited more than once.
- At any time, from your current island you may go to another not-yet-visited island by either:
- Walking: only possible when there is a bridge between and . In this case, the bridge's length is added to your total walking distance.
- Ferry: you may choose this option only when there is no combination of bridges and previously used ferries that can take you from to (when checking reachability, you should consider all paths, including those through islands you have already visited).
Note that you do not have to visit all islands, and you may not be able to walk all the bridges.
Write a program that, given the bridges and their lengths, computes the maximum sum of bridge lengths you can walk under the rules above.
Input Format
The first line contains one integer (), the number of islands in the park.
Then lines follow, each describing one island. The -th line contains two integers separated by a single space, describing the bridge built from island . The first integer is the island at the other end of the bridge, and the second integer is the bridge's length (). You may assume that for every bridge its endpoints are always on different islands.
Output Format
Output a single integer: the maximum possible walking distance.
Sample Input
7
3 8
7 2
4 2
1 4
1 9
3 4
2 3
Sample Output
24
Sample Explanation

The sample has bridges, namely and . Note that two different bridges connect islands and .
One way to achieve the maximum walking distance is:
- Start at island .
- Walk the bridge of length to island .
- Walk the bridge of length to island .
- Walk the bridge of length to island .
- Take the ferry from island to island .
- Walk the bridge of length to island .
Finally you arrive 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 this island. More precisely:
- You cannot walk there, because there is no bridge connecting island (your current island) and island .
- You cannot take a ferry there, because you can already reach island from your current island . One such way: walk the bridge, then take the ferry you already used from island to island , then walk the bridge, and finally walk the bridge.