#P9245. Skipping an Attraction
Skipping an Attraction
Skipping an Attraction
A tourist attraction park consists of \( N \) attractions, numbered \( 1 \) to \( N \). There are \( N-1 \) bidirectional ferry routes connecting the attractions, forming a tree structure. The only way to travel between attractions is by these ferry routes, and each route takes a certain amount of time.
Every day, the experienced guide Xiao Ming leads tourists through \( K \) attractions in a fixed order: \( A_{1}, A_{2}, \ldots, A_{K} \). Due to time constraints, today he decides to skip exactly one attraction. Specifically, if he skips \( A_{i} \) (\(1 \le i \le K\)), then the route will be \( A_{1}, A_{2}, \ldots, A_{i-1}, A_{i+1}, \ldots, A_{K} \).
Your task is: for each \( A_{i} \), compute the total time Xiao Ming will spend on the ferry routes if he skips that attraction. Note that the total time is the sum of the travel times between consecutive attractions in the new route.
The distance between any two attractions is defined as the sum of the weights on the unique path connecting them in the tree. In particular, if \( d(u,v) \) denotes the distance between attractions \( u \) and \( v \), and if the original route has a cost \[ T = \sum_{j=1}^{K-1} d(A_{j},A_{j+1}), \] then for a skipped index \( i \) the new route cost can be computed as follows:
- If \( i = 1 \): Answer = \( T - d(A_{1},A_{2}) \).
- If \( i = K \): Answer = \( T - d(A_{K-1},A_{K}) \).
- Otherwise, \( 1 < i < K \): Answer = \( T - d(A_{i-1},A_{i}) - d(A_{i},A_{i+1}) + d(A_{i-1},A_{i+1}) \).
You are given the tree description (the attractions and the ferry routes) and the sequence \( A_{1},A_{2},\ldots,A_{K} \). Calculate and output \( K \) numbers, where the \( i \)th number is the total travel time if attraction \( A_{i} \) is skipped.
inputFormat
The first line contains two integers \( N \) and \( K \) -- the number of attractions and the length of the planned route.
Each of the next \( N-1 \) lines contains three integers \( u, v, w \), indicating there is a bidirectional ferry route between attractions \( u \) and \( v \) with travel time \( w \).
The last line contains \( K \) integers: \( A_{1}, A_{2}, \ldots, A_{K} \), representing the order of attractions to be visited.
outputFormat
Output \( K \) integers separated by spaces. The \( i \)th integer should be the total travel time required if attraction \( A_{i} \) is skipped.
sample
5 4
1 2 3
2 3 4
2 4 2
4 5 1
1 3 4 5
7 6 14 13