Problem:
Diameter of a Tree

Given a tree T with non-negative weight, find the diameter of the tree.

The diameter of a tree is the maximum distance between two nodes in a tree.

Input

n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given.

si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output

Print the diameter of the tree in a line.

Constraints

1 ≤ n ≤ 100,000

0 ≤ wi ≤ 1,000

Sample Input 1

4
0 1 2
1 2 1
1 3 3

Sample Output 1

5

Sample Input 2

4
0 1 1
1 2 2
2 3 4

Sample Output 2

7

Solution in Go (judge verdict: Accepted)

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}

func getNextUint64(scanner *bufio.Scanner) uint64 {
	i, _ := strconv.ParseUint(getNextString(scanner), 10, 64)
	return i
}

func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}

func main() {
	fp := os.Stdin
	wfp := os.Stdout

	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
		if len(os.Args) > 2 {
			wfp, _ = os.Create(os.Args[2])
		}
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(wfp)

	n := getNextInt(scanner)
	tree := make([][]Node, n)
	for i := 0; i < n; i++ {
		tree[i] = make([]Node, 0)
	}

	for i := 0; i < n-1; i++ {
		s := getNextInt(scanner)
		t := getNextInt(scanner)
		w := getNextInt(scanner)
		tree[s] = append(tree[s], Node{
			to: t,
			w:  w,
		})
		s, t = t, s
		tree[s] = append(tree[s], Node{
			to: t,
			w:  w,
		})
	}

	sol := Solve{}

	sol.tree = tree
	sol.dist = make([]int, n)
	sol.dfs(0, -1)
	d := -1
	x := -1
	for i := 0; i < n; i++ {
		if d < sol.dist[i] {
			x = i
			d = sol.dist[i]
		}
	}
	sol.dist = make([]int, n)
	sol.dfs(x, -1)
	d = -1
	y := -1
	for i := 0; i < n; i++ {
		if d < sol.dist[i] {
			y = i
			d = sol.dist[i]
		}
	}

	fmt.Fprintln(writer, sol.dist[y])
	writer.Flush()
}

type Solve struct {
	tree [][]Node
	dist []int
}

func (sol *Solve) dfs(i, p int) {
	for _, node := range sol.tree[i] {
		if node.to == p {
			continue
		}
		sol.dist[node.to] = sol.dist[i] + node.w
		sol.dfs(node.to, i)
	}
}

type Node struct {
	to, w int
}