struct Scanner { private var elements = [String]() private var index = 0 mutating func peek() -> String { while elements.count == index { elements = readLine()!.split(separator: " ").map(String.init) index = 0 } return elements[index] } mutating func next() -> String { defer { index += 1 } return peek() } mutating func nextInt() -> Int { return Int(next())! } mutating func nextInts(_ n: Int) -> [Int] { return (0 ..< n).map { _ in nextInt() } } mutating func nextDouble() -> Double { return Double(next())! } } struct Array2D { let n1: Int let n2: Int private var elements: [Element] init(repeating: Element, _ n1: Int, _ n2: Int) { self.n1 = n1 self.n2 = n2 self.elements = [Element](repeating: repeating, count: n1 * n2) } subscript(i: Int, j: Int) -> Element { get { elements[i * n2 + j] } set { elements[i * n2 + j] = newValue } } } var scanner = Scanner() let N = scanner.nextInt() let Q = scanner.nextInt() let C = scanner.nextInt() var tree = [[(Int, Int)]](repeating: [], count: N) for _ in 0 ..< N - 1 { let u = scanner.nextInt() - 1 let v = scanner.nextInt() - 1 let l = scanner.nextInt() tree[u].append((v, l)) tree[v].append((u, l)) } var distance = Array2D(repeating: 0, N, N) func dfs(u: Int, parent: Int?, root: Int) { for (v, w) in tree[u] where v != parent { distance[root, v] = distance[root, u] + w dfs(u: v, parent: u, root: root) } } for i in 0 ..< N { dfs(u: i, parent: nil, root: i) } let X = scanner.nextInts(Q).map { $0 - 1 } let inf = Int.max / 2 var dp = Array2D(repeating: inf, Q, N) dp[0, X[0]] = 0 for i in 0 ..< Q - 1 { for j in 0 ..< N where dp[i, j] != inf { dp[i + 1, j] = min(dp[i + 1, j], dp[i, j] + distance[X[i], X[i + 1]]) } let m = (0 ..< N).map { dp[i, $0] }.min()! for j in 0 ..< N { dp[i + 1, j] = min(dp[i + 1, j], m + distance[X[i], j] + distance[j, X[i + 1]]) } func dfs(_ u: Int, _ parent: Int?) -> Int { var result = dp[i, u] + distance[u, X[i + 1]] + C for (v, _) in tree[u] where v != parent { let value = dfs(v, u) result = min(result, value) } dp[i + 1, u] = min(dp[i + 1, u], result) return result } dfs(X[i + 1], nil) } print((0 ..< N).map { dp[Q - 1, $0] }.min()!)