#P11249. Treasure Hunt on a Tree
Treasure Hunt on a Tree
Treasure Hunt on a Tree
Given a tree with \(n\) nodes, some of which contain treasures, determine whether it is possible to collect all the treasures by choosing an arbitrary starting node and moving along the tree subject to the following condition: each edge can be traversed at most once and disappears immediately after it is used.
Whenever you visit a node with a treasure, you pick it up. You are allowed to visit non-treasure nodes as needed. Your task is to decide if there exists a simple path (i.e. a path which does not reuse any edge) that visits every node containing a treasure.
Observation: In a tree, any simple path is the unique route between its two endpoints. Hence, there exists a simple path covering all treasure nodes if and only if the set of treasure nodes is collinear, meaning that if you take the two treasure nodes that are farthest apart (forming the diameter of the treasure set), every other treasure node lies on the unique path between them. Formally, let \(a\) and \(b\) be two treasure nodes such that the distance \(d(a, b)\) is maximized among all pairs in the treasure set. Then for any treasure node \(x\), it must hold that:
[ d(a, b) = d(a, x) + d(x, b)]
If the above property is satisfied for all treasure nodes \(x\), output YES
; otherwise, output NO
.
inputFormat
The first line contains two integers \(n\) and \(m\) \((1 \leq n \leq 10^5, 0 \leq m \leq n)\) representing the number of nodes in the tree and the number of nodes that have treasures respectively.
The second line contains \(m\) distinct integers in the range \([1, n]\) indicating the indices of the nodes containing a treasure. If \(m = 0\), this line will be empty.
Each of the following \(n-1\) lines contains two integers \(u\) and \(v\) \((1 \leq u, v \leq n)\) which means there is an edge between nodes \(u\) and \(v\).
outputFormat
Output a single line containing YES
if it is possible to collect all treasures along some simple path, otherwise output NO
.
sample
3 2
1 3
1 2
2 3
YES