Longest Corridor Walk

medium trees dfs graphs 1000 ms · 256 MB

Longest Corridor Walk

A museum has n rooms numbered from 1 to n, connected by n − 1 corridors. Each corridor joins two different rooms and has a length. You can get from any room to any other room through the corridors.

A night guard wants to plan the longest possible patrol. The guard starts in some room, walks through corridors and stops in some room, and never walks through the same corridor twice. The length of the patrol is the total length of the corridors walked.

Find the length of the longest possible patrol.

Input

The first line contains one integer n (1 ≤ n ≤ 2·10^5), the number of rooms.

Each of the next n − 1 lines contains three integers u, v, w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 10^9): a corridor of length w between rooms u and v.

You can get from any room to any other room through the corridors.

Output

Print one integer: the length of the longest patrol. If there is only one room, print 0.

Notes

In the first example, the longest patrol goes 3 → 2 → 4 → 5 and has length 4 + 2 + 6 = 12.

In the second example, the longest patrol goes 2 → 1 → 4 and has length 10 + 7 = 17.

The answer may not fit in a 32-bit integer.

Example 1

Input

6
1 2 3
2 3 4
2 4 2
4 5 6
4 6 1

Output

12

Example 2

Input

4
1 2 10
1 3 1
1 4 7

Output

17

Hints · reveal one at a time if you're stuck

Hint 1

The corridors form a tree, so a patrol is just the path between two rooms. Always following the heaviest corridor can fail: a light corridor may lead into a long branch. Trying every starting room is O(n²), too slow for n = 2·10^5.

Hint 2

Pick any room and find the room farthest from it. Must that room be one end of a longest patrol?

Hint 3

You are looking for the diameter of a weighted tree. Once you know one end of a longest path, how do you find the other? Watch out for 64-bit distances and deep recursion on a long chain.

report an issue Prefer your own editor? sooks prep 9 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.