We need to check if a given permutation (starting with 1) can be a BFS order of the given tree starting at vertex 1. In BFS on a tree, the ordering is not fully arbitrary. It must satisfy: The order of nodes at each level (distance from root) can be interleaved, but children of earlier visited nodes at same depth appear before children of later visited nodes at same depth? Actually BFS on a tree with arbitrary order of exploring neighbors still yields a valid BFS ordering that respects the level order: All nodes at distance d are visited before any node at distance d+1, but the relative order among nodes at the same distance can be any order, as long as within that distance the order respects the order of their parents? Let's think carefully.
BFS algorithm: start with root in queue. While queue not empty, pop front, then push all unvisited neighbors (i.e., children in tree) in arbitrary order. Since the graph is a tree, there's no cross-edge between nodes at same level from different parents except through parent. In a tree, the neighbors of node v at level L are: its parent (already visited) and its children (level L+1). So when we pop v, we will push its children (if not visited) in any order. The BFS queue maintains order: nodes are enqueued as we discover them. So the order of visiting nodes is exactly the order they are dequeued. This order must satisfy: For any two nodes u and v, if depth(u) < depth(v), then u appears before v. This is because we only push children when we process a node at current level, and all nodes at current level are processed before moving to next level because the queue is FIFO. However, there is nuance: Suppose we have nodes at same depth. They will be enqueued by their parents (which are at depth-1). The order among nodes at depth d depends on the order of processing of their parents (which are at depth d-1) and the order of children enumeration for each parent. Since the queue processes nodes in the order they are enqueued, the depth d nodes will be visited in the order they are enqueued. And they are enqueued when their parent is processed. So the sequence of depth d nodes is formed by concatenating the children lists (in arbitrary order) of depth d-1 nodes in the order those parents are processed.
Therefore, a BFS order of a tree starting from root must satisfy: The root is first. For any two nodes, if the parent of node x appears before parent of node y in the order, then all children of x (i.e., nodes whose parent is x) appear before all children of y? Not exactly: Because the children of x are enqueued when x is processed. Suppose parent order: p1, p2, p3,... Then the children of p1 are enqueued during processing of p1, then children of p2 enqueued, etc. Since queue is FIFO, children of p1 will be dequeued before children of p2 (since they are enqueued earlier). However, children of p1 could be interleaved with children of p2 if p2's children are enqueued before p1's children? But they are enqueued after p1's children because p2 is processed after p1, and during processing of p2 we enqueue its children. So indeed children of p1 appear entirely before children of p2. But careful: Could it happen that a child of p2 is enqueued before some child of p1? No, because all children of p1 are enqueued before p2 is even popped, and after p1 is popped, we enqueue all its children. Then we proceed to next element in queue, which is p2 (assuming no other nodes before p2; but if there were other nodes at same level before p1? Actually p1 and p2 are both at same depth, and they are enqueued in some order. After root is processed, we enqueue children of root. Those children are exactly all nodes at depth 1. They are enqueued in some order. Then the queue initially contains these depth-1 nodes. Then we pop the first one, say p1, and enqueue its children. Those children (depth 2) go to the end of the queue, after all other depth-1 nodes that are still in the queue. So yes, all children of p1 are enqueued before we process the next depth-1 node p2, because p2 is still in queue but after p1, and p1's children are enqueued after p2? Wait: The order: Initially queue = [root]. Pop root -> enqueue children of root in arbitrary order -> queue becomes [c1, c2, ..., ck] (depth 1). Then pop c1 -> enqueue its children (depth 2) at the end -> queue becomes [c2, c3, ..., ck, children of c1]. Then pop c2 -> enqueue its children at the end -> queue becomes [c3,...,ck, children of c1, children of c2]. So indeed, children of c1 appear before children of c2? Let's examine: After processing c1, children of c1 are appended after ck. Then when we later process c2, its children are appended after children of c1. So the order of children (depth 2) in the queue is: first all children of c1, then all children of c2, then all children of c3, etc. However, note that there are also depth-1 nodes still in the queue (c2,...,ck) that will be processed before any children of c1. But children of c1 themselves are after all remaining depth-1 nodes. So the order of visiting depth-2 nodes: they will be visited after all depth-1 nodes have been processed. Because queue has all depth-1 nodes first, then children of c1, then children of c2, etc. So indeed, all depth-1 nodes are visited before any depth-2 node. Then within depth-2 nodes, they appear in order of the parent order: children of the first depth-1 node (in order of processing) appear first, then children of the second depth-1 node, etc.
Thus, BFS ordering on a tree has a layered structure: level by level, and within each level, the nodes appear grouped by parent in the order that parents were visited in the previous level.
This property can be used to check validity.
Given a sequence a[1..n] (a[1] must be 1). We need to check if it can be a BFS order.
We can compute depths (distance from root) via BFS from root. Then the sequence must be non-decreasing in depth, and all nodes of depth d must appear before nodes of depth d+1. Additionally, for nodes at same depth, the ordering must respect the parent order condition: if we look at parents of nodes at depth d, they are at depth d-1. The sequence of these parents (as they appear when their children are listed) must be non-decreasing with respect to the order of the parents in the BFS order at depth d-1. More formally: Let orderPos[v] = index of v in the given sequence (1-indexed). For each node v (except root), let parent p = its parent in BFS tree (or in the given tree; but tree is undirected, but we root at 1). Then for any two nodes x and y at same depth, if orderPos[p_x] < orderPos[p_y] then orderPos[x] < orderPos[y] must hold? Actually we need that all children of p_x appear before all children of p_y. So for any two nodes x,y with same depth and different parents p_x and p_y, if p_x appears earlier in the BFS order than p_y, then x must appear earlier than y. However, it is possible that p_x = p_y; then children of same parent can be in any order among themselves.
But careful: The parent order at depth d-1 is the order in which those parent nodes themselves were visited (i.e., their positions in the BFS order). Since the BFS order at depth d-1 might have many nodes. The children of a parent p will be enqueued at the moment p is processed. That moment is after all earlier parents at same depth have been processed and their children enqueued. So children of p appear in the BFS order after all children of earlier parents (i.e., those with smaller orderPos among depth d-1). But also, they appear after all nodes of depth d-1 that are after p? Actually wait: The children of p are enqueued when p is processed, which is at the time when p is popped from the queue. At that point, the queue contains some nodes: possibly some remaining nodes at depth d-1 (those after p in the parent order) and all children of previously processed depth d-1 nodes. The children of p are appended after them. Then later, when we eventually get to process those children, they will be after all remaining depth d-1 nodes? Let's simulate: Depth 0: root. After root, queue = depth1 nodes in some order: say [p1, p2, p3,..., pm] (these are all depth1). Process p1: enqueue children of p1 -> queue becomes [p2, p3, ..., pm, c11, c12, ...]. Process p2: enqueue children of p2 -> queue becomes [p3, ..., pm, c11, c12, ..., c21, c22,...]. So note: before processing p3, queue has [p3,..., pm, children of p1, children of p2]. So children of p1 and p2 are after p3...pm. When we then process p3, children of p3 will be appended after children of p2. So eventually after we finish processing all depth1 nodes (p1..pm), the queue will contain: children of p1, children of p2, ..., children of pm. So the order of depth2 nodes in the queue (and thus in visit order) is: all children of p1, then all children of p2, ..., then all children of pm. However, note that while we were processing depth1 nodes, we also might have been dequeuing depth2 nodes? No, because depth2 nodes are at the end of the queue, and we process nodes in order; we won't reach a depth2 node until all depth1 nodes have been popped. Because the queue initially had only depth1 nodes. As we pop depth1 nodes, we push depth2 nodes at the back. Since we always pop from the front, we will finish all depth1 nodes before we get to the first depth2 node. So indeed, all depth1 nodes are visited before any depth2 node. So the final depth2 order is exactly concatenation of children lists of depth1 nodes in the order that their parents were visited.
Thus the condition: For any two nodes u, v at same depth, let p_u, p_v be their parents. If orderPos[p_u] < orderPos[p_v] then orderPos[u] < orderPos[v]. (Because children of earlier parent appear before children of later parent). Also, for children of same parent, there is no restriction; any order is fine.
But is this condition both necessary and sufficient? For a tree, BFS order from root must satisfy that, and conversely, any order that satisfies these conditions (plus start at root, and all nodes appear exactly once) can be realized by a BFS with appropriate neighbor order. I think yes: You can choose to explore children in the given order for each parent, and the BFS will produce exactly that sequence provided the parent order condition holds. But need to ensure that the parents are indeed visited in that order (the order of depth d-1 nodes as given). Since we can control neighbor order for each parent, we can produce the desired order of children for each parent. However, we also need that the order of parents themselves matches the given order at depth d-1. This is recursively satisfied if the sequence satisfies the condition for all depths. Because root is first, depth1 nodes appear in some order; they must be children of root. That order can be any permutation of root's children. Then for depth2, they must be grouped by parent (depth1) and within each group in any order, and the groups must appear in the same order as the parents appear in depth1. This matches the BFS constraints. So algorithm: Validate that a[1]=1. Build tree adjacency. Root the tree at 1, compute parent and depth (BFS from 1). Then check:
- For each depth level, the nodes appear in non-decreasing depth order (i.e., depth[a[i]] <= depth[a[i+1]]). Actually BFS ensures that all nodes of depth d appear before any node of depth d+1, so depth should be non-decreasing, and strictly increasing only when moving to next level. So we can verify: depth[a[i]] <= depth[a[i+1]] and also first node depth=0 then depth=1 etc. But we can more simply check the parent ordering condition which will enforce this as well. But easier: check that for any i<j, if depth[a[i]] > depth[a[j]] then invalid. But we only need to check order: depths must be non-decreasing. However, note that BFS order could have same depth nodes in any order, so non-decreasing is necessary but not sufficient. So we need both non-decreasing depth and the parent order condition.
But is non-decreasing depth automatically enforced by parent order condition? Possibly yes if root is first. Let's see: For any node v (depth d), its parent has depth d-1. The condition only relates nodes at same depth. It doesn't directly enforce that a node of depth d+1 cannot appear before depth d node. However, if we have a sequence that satisfies parent ordering at each depth, does it guarantee that depths are non-decreasing? Suppose we have root, then a node of depth 2 appears before a node of depth 1. That would violate parent ordering? Because depth2 node's parent is depth1, which hasn't appeared yet. But the condition for depth2 node would compare its parent with other depth2 nodes' parents. However, it doesn't compare with depth1 nodes. So we need separate check for depth monotonicity.
But maybe we can incorporate by using the idea of BFS order verification algorithm: Simulate BFS with given order and check if it's possible. Let's consider alternative approach: Simulate BFS using queue, but we must decide which neighbor to push when processing a node. Given a candidate order, we can try to verify by walking through the sequence and maintaining a queue of nodes that are expected to be processed. However, due to arbitrary neighbor order, the BFS process can be simulated if we know the order in which children are to be visited? Actually we can try to reconstruct: start with root=1. The sequence tells us the order of visited nodes. We need to see if we can assign each node's children in the tree such that when we process nodes in the given order, we can push children appropriately.
I recall known solution for problem "BFS on tree" or "BFS order" (CF problem). Typical approach: Compute depth and parent using BFS. Then for each node, we note the order in which its children appear in the sequence. Check if for each node, its children appear as a contiguous block in the sequence, sorted by the order of parents. But is it contiguous? Let's think: Suppose we have two parents p and q at same depth. Their children appear in the BFS order as a block: all children of p (in any order) then all children of q (in any order). Is it always contiguous? Yes, because after finishing processing p, we enqueue its children; later when we process q, we enqueue its children after p's children. So all children of p appear consecutively? Actually not necessarily consecutively if there are other nodes at same depth? At depth d, the children of p are depth d+1. But among depth d+1, the children of p appear before children of q. However, are there any other nodes at depth d+1 that could interleave? Only other depth d+1 nodes are children of other parents at depth d. Since those parents appear after p, their children come after p's children. So children of p form a contiguous segment in the depth d+1 sequence. But note that depth d+1 nodes may not be contiguous overall in the full sequence because depth d nodes are interleaved? Actually depth d nodes appear before depth d+1 nodes, as we argued. So depth d+1 nodes appear as a contiguous block after all depth d nodes? Let's examine: At the start, root (depth0). Then depth1 nodes appear as a block? In BFS, after processing root, we enqueue all children of root (depth1). Then we process depth1 nodes in order, and while processing each depth1 node, we enqueue its children at the back. But those children (depth2) are enqueued while we are still processing depth1 nodes? Wait, we enqueue children of first depth1 node before we finish processing all depth1 nodes. But those children are placed after the remaining depth1 nodes in the queue. So they won't be visited until after all depth1 nodes have been visited, because the queue order is: after processing root, queue = depth1 nodes. Then we pop first depth1 node, process it, and push its children to the back. Now queue = (remaining depth1 nodes) + (children of first). So the next node to pop is the second depth1 node. So indeed, we continue popping depth1 nodes until none left. Only then will we start popping depth2 nodes. So all depth1 nodes are visited before any depth2 node. So depth levels are contiguous blocks in the BFS order: first block depth0 (root only), then block depth1, then block depth2, etc. This holds for BFS on a tree (since no edges skip levels). For general graphs, BFS may interleave levels due to cross edges, but tree ensures levels are exactly layered. So the sequence must be level-order: nodes of each depth form a contiguous segment in the order.
Thus we can check that the sequence is grouped by depth: i.e., if we list depths in order, they should be non-decreasing and there should be no "dip" back to earlier depth after moving to later depth. Actually after we move to depth d+1, we never go back to depth d. So depths should be non-decreasing, and if depth increases, it never decreases. So we can compute depths and ensure that for all i, depth[a[i]] <= depth[a[i+1]].
Given that, the sequence within each depth must satisfy the parent grouping property.
Now we need to verify: For depth d+1 nodes, they are children of nodes from depth d. Let the depth d nodes appear in some order P = [p1, p2, ..., pk] (as they appear in the sequence). For each depth d+1 node v, we can identify its parent (unique, because tree). Then the sequence of depth d+1 nodes must be such that if we look at the parents in order of appearance of their children, it should be non-decreasing: i.e., the list of parents (when we map each child to its parent) must be sorted in the same order as P, and for each parent, the children of that parent appear consecutively? Actually not necessarily consecutively? Let's think: If children of p1 appear as a block, then children of p2 appear as a block, etc. That means the sequence of parents for depth d+1 nodes is like: p1 repeated deg1 times, then p2 repeated deg2 times, etc. So it's sorted non-decreasing relative to the order of parents. Conversely, if the sequence of parents is non-decreasing, does it guarantee contiguous blocks? If there is mixing, like p1, p2, p1 again, that would violate non-decreasing because p1 > p2? Actually order of parents is based on their appearance order: p1 appears before p2 in depth d. So if we assign numbers according to their index in depth d order: ord(p1)=1, ord(p2)=2,... Then the sequence of ord(parent) for depth d+1 nodes must be non-decreasing. And if it's non-decreasing, then it implies that all children of parent with smaller ord appear before those with larger ord. However, it does not require that children of the same parent appear contiguously? Actually if it's non-decreasing, children of same parent will appear in a block because if you have multiple entries of the same parent, they can be interspersed with other parents only if the order is not strictly increasing but allows equal? Non-decreasing allows equal, but if we have p1, p2, p1, the ord would be 1,2,1 which is decreasing at the third element (1 after 2). So that violates non-decreasing. So non-decreasing ensures that once we move to a parent with higher ord, we never go back to a lower ord. That implies that for each parent, its children appear in a contiguous segment (possibly empty). Because all children of parent with ord = x appear together, then children of ord = y > x appear together, etc. So contiguousness is equivalent to the sequence of parent ord being non-decreasing. So it's enough to check that for each level, when we list the parents of nodes at that level in the order they appear, those parent indices (according to their position in previous level) are non-decreasing.
But we must also ensure that the set of parents for depth d+1 nodes is exactly the depth d nodes that actually have children, and each child appears exactly once. That is automatic if the tree structure matches.
So the verification algorithm:
- Build adjacency list.
- Perform BFS from 1 to compute depth of each node (or DFS). Also compute parent (in BFS tree, but since tree is unrooted, we can root at 1 and assign parent as the node from which we first discovered it).
- Check that a[1] = 1.
- For i from 2 to n: ensure depth[a[i]] >= depth[a[i-1]]. Actually we need non-decreasing, so depth[a[i]] >= depth[a[i-1]]? Wait: depth increases as we go deeper. So depth[a[i]] should be >= depth[a[i-1]]? Actually depth of root is 0, depth of children is 1. So as we move along sequence, depth is non-decreasing? It should be monotonic non-decreasing because we finish all nodes of current depth before moving to next. So depth[a[i]] >= depth[a[i-1]]? But depth can stay same (same level) or increase to next level. It should never decrease. So condition: depth[a[i]] >= depth[a[i-1]]. Yes.
But careful: Could there be a scenario where depth increases by more than 1? In BFS on tree, nodes of depth d+1 come after all nodes of depth d, so depth can only increase by 1 at the point where we transition from depth d to depth d+1. It cannot jump from depth d to d+2 because all nodes at depth d+1 would appear before depth d+2. However, if the tree has only nodes at depth d and d+2 but none at depth d+1? Not possible because tree is connected and root to depth2 must go through depth1. So depth values are contiguous, but in sequence, depth might increase by 1 at the boundary between levels. However, there could be nodes of depth d+1 missing? Actually if a node has depth d+2, it must have a parent at depth d+1, so depth d+1 nodes exist. But those depth d+1 nodes might appear earlier. So in the BFS order, all nodes of depth d+1 appear before any depth d+2. So depth sequence is like: some number of 0's (just 1), then some number of 1's, then some number of 2's, etc. So depth is non-decreasing, and increases by at most 1 each step, but it's not strictly necessary to check step size? Actually it can stay same or increase by exactly 1 at boundaries. However, it's possible that depth increases by 0 or 1; it cannot increase by more than 1 because if it increased by 2, that would skip a level. That would be invalid because there must be nodes of the intermediate level earlier, but they would have to appear before. But could depth increase by 2 from one index to the next? Suppose at index i we have depth d, at i+1 we have depth d+2. That would mean a node of depth d+2 appears before some depth d+1 nodes? But maybe depth d+1 nodes exist and should appear earlier; they haven't yet appeared, so invalid. So we can also enforce that depth[a[i]] - depth[a[i-1]] is either 0 or 1, and when it's 1, it happens only at the first node of new level. However, it's enough to check non-decreasing and also that for each node, its depth is depth[parent]+1. Actually we can incorporate that later. But we can just check non-decreasing; the parent condition will likely catch violations.
Now the main check: For each depth level from 0 upwards, we need to validate ordering of nodes at that level. Let's define for each depth d, the list of nodes at that depth in the order they appear in sequence. For root depth 0, it's just [1]; it's fine.
Now for depth d >= 1, we have list L_d (nodes at depth d). Their parents are at depth d-1. Let P_{d-1} be the list of nodes at depth d-1 in the order they appear. We assign each node in L_d a parent. For the ordering to be valid, the sequence of parents (when we iterate L_d) must be such that the indices of these parents in P_{d-1} are non-decreasing. Because children of earlier parent (in P_{d-1}) must come before children of later parent.
But careful: Could there be a node at depth d whose parent is not in P_{d-1}? By construction of depth, its parent must be at depth d-1, so it's there. However, note that the parent might not appear in P_{d-1}? Actually parent is at depth d-1, so it must be in the list of nodes at that depth. And since we are scanning whole sequence, all nodes appear. So it's fine.
Thus algorithm:
-
Compute depth array (BFS from 1) and parent array (the immediate parent in rooted tree). For root, parent=0.
-
Verify a[1]==1.
-
Optionally verify depths are non-decreasing (if not, print No). This may also be covered by parent ordering, but better to check explicitly.
-
Preprocess positions: pos[v] = index of v in the given sequence (1-based). This helps for parent ordering.
-
For each depth level d from 1 to maxDepth, gather nodes at that depth in the order they appear in the sequence. That is: iterate through a[1..n] and if depth[a[i]]==d, add a[i] to list for depth d. Because the sequence is in BFS order, levels are contiguous, so we could also find boundaries. But safer to just collect by scanning sequence and appending to vector per depth.
-
Also for depth d-1, we have list of nodes in order. But we also need to map each node to its order index within its depth level. So for each depth d-1, create a mapping orderInLevel[v] = its index (1-based) in the list for that depth. Because we compare parent order: parent p's order among depth d-1 nodes.
-
Then for depth d (starting from 1), we iterate through its list (children in order). For each node v in that list, let p = parent[v]. If p is not in depth d-1? It must be, but we can assert. Then we consider the order index of p: idx = orderInLevel[p] (which is its position among depth d-1 nodes). The sequence of these idx values as we go through depth d nodes must be non-decreasing. Also we must ensure that for each parent, its children appear only after the parent itself appears in the sequence? But that is automatic because depth d-1 nodes appear before depth d nodes, and parent has depth d-1, so it appears earlier. But we need to ensure that for each child, its parent actually appears earlier in the overall sequence? Since depth d > depth d-1, and the sequence groups by depth, the parent appears earlier. But also need to ensure that the parent appears before its children? In BFS, parent is visited before its children (since children are discovered when parent is processed). In the sequence, parent depth is lower, so it appears earlier. So that's fine.
However, we must also consider that BFS might have "cousins" from different parents but still depth same; condition ensures ordering relative to parents.
But is the condition of non-decreasing parent indices sufficient? Let's test with sample invalid: 1 2 4 3. Tree: edges: 1-2,1-3,2-4. Depths: depth1=0, depth2: nodes 2,3 (depth1), depth4: node4 (depth2). The sequence: a = [1,2,4,3]. Depth: 0,1,2,1. So depths not non-decreasing (2 then 1) -> fails non-decreasing check. So output No.
Another valid: 1,2,3,4: depths: 0,1,1,2. Depth non-decreasing: 0->1 (ok),1->1 (ok),1->2 (ok). Now level1 (depth1) nodes: [2,3] order. Level2 nodes: [4]. Parent of 4 is 2. OrderInLevel of parents at depth1: order: 2 at index1, 3 at index2. For depth2 list [4], parent idx =1. Non-decreasing trivially. So passes.
Other valid: 1,3,2,4: depth1 nodes: [3,2]; orderInLevel: 3:1, 2:2. depth2: [4], parent=2, idx=2. Non-decreasing? idx=2 is ok. So passes.
But consider a more complex example: Suppose tree: 1-2,1-3,2-4,2-5,3-6,3-7. Valid BFS orders: children of 2 must appear together, children of 3 together, and the groups must appear in order of 2 and 3 as they appear in depth1. So if depth1 order is [2,3], then depth2 order must be [4,5,6,7] or [4,5,6,7] but also could be [4,5,6,7] (children of 2 in any order, then children of 3 in any order). Could there be an order like [4,6,5,7]? That would be: children of 2 (4), then child of 3 (6), then child of 2 (5), then child of 3 (7). That violates parent order because parent indices: 2 (idx1), 3 (idx2), 2 (idx1) -> non-decreasing fails because after idx2 we have idx1. So our check would reject. That is correct.
But what about cases where some parent has no children? Then that parent's index is skipped; the non-decreasing condition still holds because children of later parents will have larger indices.
Now consider if the sequence satisfies non-decreasing parent indices but depth not non-decreasing? Could that happen? Possibly if there is a node of depth d+1 appearing before a node of depth d (with d same as or less than?). For example, root is depth0, then depth2 node appears before depth1 node. Parent of depth2 node is depth1. In that case, the depth1 parent hasn't appeared yet. So the parent order condition for depth2 would involve parent index of that node. However, if the depth1 node hasn't appeared yet, then its orderInLevel among depth1 nodes is not defined because we haven't placed it in the depth1 list (since we construct lists from the sequence). Actually when we collect nodes by depth from the sequence, depth1 list would contain nodes of depth1 in order of appearance. If a depth2 node appears before some depth1 node, then in the sequence we would have: ... (some depth2) then later (depth1). But since depths must be grouped, this would cause depth1 node to appear after depth2 node, making depth list for depth1 include that node after some depth2 node? But our method of grouping by depth from the sequence: we iterate over the whole sequence and assign each node to its depth list in the order they appear. So if depth2 appears before depth1, the depth1 list will still have that depth1 node later. Then the depth2 list will have a node that appears before its parent in the overall sequence? That might still pass the non-decreasing parent condition? Let's test: Suppose we have tree: 1-2, 2-3. So depths: 1:0,2:1,3:2. Suppose sequence: [1,3,2]. Depth1 list: [1] (depth0), depth1 list: [2]? Actually depth1 node is 2, but in sequence it's after 3. So depth list for depth1 would be [2] (only one node, order index 1). Depth2 list: [3]. Parent of 3 is 2. orderInLevel[2] = 1. So parent idx=1, non-decreasing trivially. But depths: 0 -> 2 -> 1, not non-decreasing (2 > 1). So we need to check depth monotonicity separately. So condition of non-decreasing parent indices does not catch this because the depth1 parent appears later in sequence but still gets order index 1 (since it's the only one at its depth). So we must enforce that nodes of smaller depth appear before nodes of larger depth. So we need to check depth monotonicity.
Also need to ensure that the root is first. Already check a[1]=1.
Additionally, we need to ensure that the parent relationship matches the given tree: each node (except root) has exactly one parent; but we already have parent from BFS tree. However, note that in BFS from 1, the parent of a node is its unique neighbor that is closer to root. But could there be alternative BFS trees? Actually for a given tree, BFS from root will always produce the same set of parents if we consider the tree rooted at 1: the parent is the neighbor with depth = depth(v)-1. This is uniquely determined because in a tree there's exactly one such neighbor (the one on shortest path to root). So parent is fixed. So we can compute it via BFS.
Thus algorithm:
- Input n, edges.
- Build adjacency list.
- BFS from 1 to compute depth and parent (parent[1]=0). Use queue, standard BFS.
- Read sequence a[1..n].
- Check a[1] == 1.
- For i=2..n: if depth[a[i]] < depth[a[i-1]]: print No and exit. (Optionally also check that depth difference <=1? Not necessary but we can check if depth[a[i]] - depth[a[i-1]] > 1: invalid because then there is a level skipped? However, it's possible that depth increase is exactly 1 at boundaries. But if depth jumps from 0 to 2, that would be invalid because depth 2 node's parent is depth 1, which must appear earlier. But our monotonicity check only ensures non-decreasing, so 0->2 is allowed (2 >= 0). So we need to ensure depth increases at most by 1? Actually consider valid BFS: depths are contiguous blocks; when we go from last node of depth d to first node of depth d+1, the depth increases by 1. Could there be a scenario where depth increases by 0 for a while then jumps by 1? That's fine. But if depth increases by more than 1, that would mean a node of depth d+2 appears before some depth d+1 node, which violates the property that all nodes of depth d+1 appear before depth d+2. However, it's possible that there is no node of depth d+1? In a tree, if a node of depth d+2 exists, there must be a node of depth d+1 (its parent). That parent is also a node in the tree, and will be in the BFS order. Since BFS visits all nodes, that parent must appear somewhere. Could it appear after the depth d+2 node? In valid BFS order, no, because parent has smaller depth, so it appears earlier. So if depth jumps from d to d+2, it's invalid. So we should enforce that depth[a[i]] <= depth[a[i-1]]+1? Actually we can check that depth[a[i]] - depth[a[i-1]] <= 1 and depth[a[i]] >= depth[a[i-1]]. But careful: depth could stay same, then increase by 1 at boundary, then stay same, then increase by 1, etc. So we can check that depth never decreases and never increases by more than 1. But is that necessary? Suppose we have depth sequence: 0,1,1,2,2,3,... It's fine. If we have 0,1,2,1, it's invalid because depth decreases. If we have 0,2,1,... invalid because depth first increases from 0 to 2 (jump >1) then decreases. So we can check depth[a[i]] - depth[a[i-1]] is either 0 or 1. That is stricter than necessary? Consider a tree where there is a node of depth 0 (root), then maybe no depth 1? But root always has at least one child if n>1, but it's possible n=1, only root. Then depths: only 0. Sequence: [1] passes. For n>1, depth 0 then depth 1 appear. Could depth jump from 0 to 2? No, because 2's parent would be depth 1, but root's children are depth 1. So indeed depth cannot jump more than 1. However, what about after depth 1, could we jump to depth 3? No, because parent of depth 3 is depth 2, so depth 2 must exist. So depth increments by at most 1. So we can safely enforce depth[a[i]] - depth[a[i-1]] <= 1 for all i. But is there any valid BFS order where depth stays same then jumps by 1 then stays same then jumps by 1, etc. That's allowed. So condition: depth[a[i]] - depth[a[i-1]] is 0 or 1. Additionally, depth cannot decrease. So combine: depth[a[i]] >= depth[a[i-1]] and depth[a[i]] <= depth[a[i-1]]+1.
However, is it possible for depth to increase by exactly 1 at some point but then later also increase by 1 again? That's fine. So this condition is necessary.
But is it sufficient along with the parent ordering? Possibly yes. However, we must also consider that depth may increase by 1 at multiple points, but that's okay as long as the levels are contiguous in order: e.g., 0,1,1,2,1? That would violate non-decreasing. So we already have non-decreasing plus max increase 1.
Now after these checks, we proceed to the parent order condition.
We need to group nodes by depth. Since n up to 2e5, we can create vector<vector> levels(maxDepth+1). Iterate through a, and push each node into levels[depth[node]]. Also we need orderInLevel for each node: its position (index) within its level list.
We can compute an array orderInLevel of size n+1. Iterate over levels: for each level d, for index j from 0 to size-1, set orderInLevel[levels[d][j]] = j (0-index or 1-index). Use 0-index for convenience.
Then for each level d from 1 to maxDepth, we consider the list L = levels[d]. For each node v in L, let p = parent[v]. Since depth[v] = d, depth[p] = d-1. Then get idx = orderInLevel[p] (its index in level d-1). Then as we iterate L, we check that the sequence of idx is non-decreasing. That is, keep a variable prev_idx = -inf, and for each v, if idx < prev_idx, then invalid. Also we need to ensure that p is indeed at depth d-1. It should be, but if there is an error (maybe due to incorrect depth calculation?), we can check.
Additionally, we should ensure that for each node v (except root), its parent appears in the sequence before it? Since depth[v] > depth[parent], and levels are contiguous, parent should appear in earlier level; but because we check depth monotonicity, it's guaranteed that parent appears earlier in the sequence? Not exactly: It's possible that depth[parent] < depth[v] but parent could appear later if depth monotonicity is satisfied? Suppose depths: parent depth 1, child depth 2. In sequence, we could have depth1 node after some depth2 node? No, because depth monotonicity ensures depth non-decreasing. So depth1 nodes appear in block before depth2 block (since depth increases only at boundaries, but it's possible that depth1 nodes and depth2 nodes are interleaved if depth monotonicity only ensures non-decreasing? Actually non-decreasing allows: depth 1, then depth 2, then depth 1 again? That would be a decrease: 2 > 1 later, so violates non-decreasing. So with non-decreasing, once we go to depth 2, we cannot go back to depth 1. So all depth1 nodes appear before any depth2 node. Therefore parent (depth1) will appear before child (depth2). So it's safe.
Now is the non-decreasing parent index condition sufficient? Let's test some tricky cases.
Consider a tree where a node has multiple children. The children can appear in any order, so the parent index for children of same parent will be the same, so non-decreasing holds (equal allowed). So that's fine.
Now consider if there is a node that is not a child of any depth d-1 node? That would mean its depth is d but parent depth is not d-1? That can't happen because we computed parent via BFS, so depth difference is exactly 1.
Now, what about the situation where the BFS ordering might have some nodes at same depth but from different parents, and the parent order condition is satisfied, but maybe there is an issue about when the parents themselves were discovered? For the BFS to produce the given order, we need that when we process the depth d-1 nodes in the given order, we can enqueue children in the order they appear in depth d list. But this is possible if the children are grouped by parent in the non-decreasing order. Because when we process parents in order, we can choose to output their children exactly in the order they appear in the depth d list, as long as the children of each parent appear consecutively and in the correct relative order among parents. So it seems sufficient.
But we must also ensure that the parent of a node indeed is adjacent (edge) in the tree. We already computed parent via BFS; that ensures that.
One more nuance: The parent we computed via BFS from root may not be the actual parent in the BFS order if there are multiple shortest paths? In a tree, each node has a unique path to root, so the parent is the neighbor with smallest depth. That is the parent in any BFS tree from root because BFS explores level by level. So it's correct.
Thus algorithm seems correct.
Edge Cases:
Let's test with additional examples.
Example: Tree: 1-2, 1-3, 2-4, 3-5. Possible valid orders: 1,2,3,4,5; or 1,3,2,5,4; or 1,2,3,5,4? Wait: In BFS, children of 2 and 3 must be in blocks: if order of depth1 is [2,3], then depth2 order must be [4,5] (children of 2 then 3) or [4,5] but if children of 2 are [4] and children of 3 are [5], then block for 2 is just 4, block for 3 is 5, so order must be 4 then 5. Could it be 5 then 4? That would require parent order for depth2 to be [3,2] but parents order at depth1 is [2,3] (since 2 appears before 3). So 5 (parent 3) has parent idx 2, 4 (parent 2) has parent idx 1; sequence would be parent idx 2 then 1 -> decreasing, invalid. So 1,2,3,5,4 is invalid. Our check would catch: depth2 list [5,4] -> parent idx [2,1] not non-decreasing. So good.
But is there any valid BFS ordering where the children of a parent are not contiguous but the parent order index condition still holds? Non-decreasing condition would force contiguity because if parent indices are non-decreasing, then all children of parent p (with index i) appear together because if we have child of parent with index i, then later child of parent with index j>i, then later another child of parent i, that would be index i after j, decreasing. So they must be contiguous.
Thus condition is correct.
Now consider a scenario where the tree has nodes with same depth but the BFS order could have interleaving children from different parents if we process neighbors in a different manner? Wait, is it absolutely required that children of earlier parent appear before children of later parent? Let's revisit BFS process more carefully. The queue initially contains root. After processing root, we enqueue all its children (depth1) in some order; say we push them in order c1,c2,c3,... So the queue becomes [c1,c2,c3,...]. Then we pop c1. While processing c1, we enqueue its children (depth2). Those children are placed at the end of the queue, after c2,c3,... So the queue becomes [c2,c3,..., children of c1]. Next we pop c2, process it, enqueue its children at the end: queue becomes [c3,..., children of c1, children of c2]. Continue. So after processing all depth1 nodes, the queue contains (children of c1, children of c2, children of c3, ...) in that order. Then we start popping depth2 nodes: first children of c1 (in the order we enqueued them), then children of c2, etc. So yes, children of earlier depth1 node appear before children of later depth1 node. So the grouping property holds.
But what if we consider BFS on a tree where we may have multiple roots? No.
Thus our conditions are necessary.
Now we should confirm sufficiency: Given a sequence that satisfies: (1) a[1]=1, (2) depths non-decreasing and increasing by at most 1, (3) for each depth level d>=1, the parents of nodes at depth d, when listed in the order of nodes at depth d, have indices (according to order of nodes at depth d-1) that are non-decreasing. Then can we construct a BFS neighbor ordering that yields exactly that sequence? We can simulate: We'll process nodes in the given order. We'll maintain a queue representing the BFS queue. At start, queue contains root. Then we iterate through the sequence (starting from the second element). For each node we encounter, it must be the front of the queue? Actually in BFS, the order of visited nodes is the order they are popped from the queue. So given the sequence a, we can simulate: we have a pointer i=2...n. We'll maintain a queue of nodes that are currently in the BFS queue (the ones that have been discovered but not yet processed). Initially after processing root, we enqueue all children of root? But we don't know the order of enqueuing yet. Alternatively, we can think of building the BFS tree gradually. The conditions guarantee that we can assign children to parents appropriately.
One known approach: For each node in order, we need to check that its parent is "ready". But the method with parent order indices is standard solution for this problem (I've seen Codeforces problem 1037D? Actually there is CF problem "Valid BFS?" 1037D? Let's recall: Problem "1037D - Valid BFS?" is exactly this. The solution is to simulate BFS with given order, using a queue and checking that at each step, the next node to be processed is among the not-yet-visited neighbors of the current processing node? Many solutions use a simpler approach: For each node, maintain a set of its neighbors. Then simulate BFS: start with queue containing 1, mark visited. For each node in the given sequence (starting from index 2), we check if it is a neighbor of the node at the front of the queue? But that's not exactly because the front may have multiple children; we need to consume them in any order. There is a known solution: Use an array of positions in the given order, then for each node sort its adjacency list according to that position. Then run BFS with that order and compare to given sequence. But that is O(n log n). However, the parent order condition is also common.
Given constraints up to 2e5, we can implement O(n) solution with BFS to compute depth and parent, then do checks.
But careful: The BFS we run to compute depth and parent is independent of the given order. That is fine.
Now check complexity: O(n) to BFS, O(n) to compute depths and parents, O(n) to build levels and orderInLevel, O(n) to verify parent indices.
Let's test on some tricky examples.
Example: Tree: 1-2, 1-3, 2-4, 4-5. depths: 1:0, 2:1,3:1,4:2,5:3. A possible valid BFS order? Let's list all BFS orders: Root 1. Depth1: order of 2,3. If order [2,3], then when processing 2, enqueue its child 4; queue becomes [3,4]. Then process 3 (no children). Then process 4, enqueue 5; then process 5. So order: 1,2,3,4,5. If order [3,2], then queue after root: [3,2]; process 3 (no children), queue becomes [2]; process 2, enqueue 4; queue [4]; process 4, enqueue 5; process 5. Order: 1,3,2,4,5. So only those two? What about 1,2,4,3,5? Let's see if possible: After root, queue [2,3] (if we push 2 then 3). But if we want to visit 2 then 4 then 3, that would require after processing 2, we enqueue 4; queue becomes [3,4]; next to pop is 3, not 4. So can't. If we push children of root in order [2,3], then 4 appears after 3. If we push [3,2], then order after root: [3,2]; then 3, then 2, then 4. So 4 after 2. So 1,2,4,3,5 invalid. Our checks: depth sequence for [1,2,4,3,5] = 0,1,2,1,3 -> not non-decreasing because 2>1 at index 4. So fails.
Now consider a more subtle case: Suppose tree: 1-2, 1-3, 2-4, 2-5, 3-6. Valid order: 1,2,3,4,5,6 (depth1:2,3; depth2:4,5,6). Another order: 1,2,3,4,6,5? Let's check if possible: After root, push children say [2,3]; queue [2,3]; pop 2, enqueue 4,5 -> queue [3,4,5]; pop 3, enqueue 6 -> queue [4,5,6]; then order: 4,5,6. So 6 appears after 5. To get 4,6,5, we would need after processing 2, queue [3,4,5]; then process 3 before 4? Actually to get 4 then 6 then 5: after processing 2, queue [3,4,5]; if we then process 3 (pop front), we get order: 2,3,... then after processing 3, enqueue 6: queue becomes [4,5,6]; then order continues 4,5,6. So 6 after 5. So 4,6,5 impossible. Our condition: depth2 list [4,6,5]; parents: 2,3,2 -> parent indices: orderInLevel of depth1 (assuming depth1 order [2,3]): 2->index0, 3->index1, 2->index0. Sequence of indices: 0,1,0 -> not non-decreasing (1 then 0). So fails.
Now consider a case where depths are fine and parent indices non-decreasing, but perhaps something else is violated? For example, maybe the parent of a node is not adjacent? But our parent array is from BFS; it is adjacent by definition. So that's fine.
What about scenario where the given sequence has correct parent indices but the actual tree structure might allow alternative parent? For instance, if a node at depth d could have multiple possible parents at depth d-1? In a tree, each node has exactly one parent when rooted at 1 because the path to root is unique. So no ambiguity.
Thus algorithm appears correct.
But there is a nuance: The BFS algorithm does not require that we only push children when we process a node; it pushes all unvisited neighbors. In a tree, the only unvisited neighbor of a node is its children (except root). So it's fine.
Now let's think about potential pitfalls: Our BFS to compute depth and parent uses standard BFS, which assumes the tree is unweighted. That's fine.
Now check condition: For each node v (except root), we need its parent p. But what if the given sequence implies a different BFS tree? Actually the BFS tree from root is unique in terms of parent-child relationships based on distances: the parent is the neighbor with smaller depth. That is fixed. In any BFS traversal starting from root, the discovery of nodes will respect those parent-child relationships: each node is discovered (first visited) when processing its parent (or possibly another node at same level? In a tree, a node at level d can only be discovered from its parent at level d-1, because any other node at level d-1 is not adjacent (tree has no cross edges). Could a node be discovered from a sibling? No, because siblings are not connected. Could a node be discovered from its child? That would be from a node at level d+1, but that node hasn't been visited yet when discovering a node at level d (since BFS processes level by level). So yes, each node's parent in the BFS tree is exactly the unique neighbor closer to root. So it's fixed. So we can compute it.
Thus our check is solid.
Now let's consider a scenario where the sequence is [1,2,4,3] for the tree 1-2,1-3,2-4. We already saw depth monotonicity fails. So fine.
Now consider a scenario where depths are non-decreasing but parent indices not non-decreasing. For example, tree as above with order [1,2,3,5,4,6]? Actually let's construct tree: 1-2,1-3,2-4,2-5,3-6. Depth1 order [2,3] (given sequence: 1,2,3,5,4,6). Depths: 0,1,1,2,2,2? Wait compute: 4 depth2,5 depth2,6 depth2. Sequence: 1(d0),2(d1),3(d1),5(d2),4(d2),6(d2). Depths: 0,1,1,2,2,2 - non-decreasing, increase by 1 at boundaries? 1->1 ok, 1->2 ok. Parent indices: depth2 list = [5,4,6]; parents: 2,2,3? Actually 5's parent is 2, 4's parent is 2, 6's parent is 3. With depth1 order [2,3], indices: 2->0, 3->1. So parent idx sequence: 0,0,1 -> that's non-decreasing (0,0,1) yes! But is this order valid? Let's test if BFS can produce 1,2,3,5,4,6. After root, enqueue children of root: order must be [2,3] to get 2 then 3. Then queue = [2,3]. Pop 2: enqueue its children. Children of 2 are 4 and 5. Order of enqueuing can be arbitrary. Suppose we enqueue 5 then 4. Then queue becomes [3,5,4]. Pop 3: enqueue its child 6. Queue becomes [5,4,6]. Then visited order: after 1,2,3, next is 5, then 4, then 6. So order: 1,2,3,5,4,6. That is exactly the sequence! So it's valid. Wait our earlier thought was maybe invalid? Let's re-evaluate: In tree: edges: 1-2,1-3,2-4,2-5,3-6. BFS: root=1. After processing 1, push children {2,3} in some order. If we push 2 then 3, queue = [2,3]. Process 2: push its children {4,5} in some order, say 5 then 4 -> queue = [3,5,4]. Process 3: push 6 -> queue = [5,4,6]. Then process 5,4,6. So order = 1,2,3,5,4,6. So yes, it's valid. So our condition (non-decreasing parent indices) says it's valid because depth2 list [5,4,6] gives parent idx [0,0,1] which is non-decreasing. So that's correct. But earlier I thought that children of same parent need to be contiguous. In [5,4,6], children of 2 are 5 and 4 (but they are not contiguous? Actually they are contiguous: 5 and 4 are both children of 2, they appear consecutively? Here they are 5 and 4, which are two nodes, and then 6 (child of 3). So children of 2 are 5 and 4, which are contiguous as a block (positions 1 and 2). So it's fine even though the order within the block is arbitrary (5 then 4). So parent indices sequence is 0,0,1 -> all children of parent 0 appear before parent 1's children. That's non-decreasing, and indeed they are contiguous (two 0s then 1). So condition is fine.
Now consider a case where parent indices non-decreasing but not contiguous? Could non-decreasing but not contiguous happen? For example, indices: 0,1,0? That's decreasing. Non-decreasing forces that once we move to a higher index, we never go back. So the indices form a sequence that can stay constant, then increase, then stay constant at the new value, etc. This implies that for each parent index value, all occurrences of that index appear in a contiguous block because if we had index i, then later index j>i, then later index i again, that would be a decrease. So contiguity is enforced.
Thus condition is equivalent to grouping.
Now, what about the scenario where some node at depth d has a parent that appears later in the depth d-1 list? That would be caught by depth monotonicity? Actually if parent appears later, then the parent's depth is d-1, and since depth d nodes appear after all depth d-1 nodes? Wait, depth d nodes appear after all depth d-1 nodes? In valid BFS, yes, because all nodes of depth d-1 are visited before any depth d node. So parent must appear before child. So if parent appears after child in the sequence, then depth monotonicity would be violated because child has depth d, parent depth d-1, but child appears before parent. Since depth(parent) < depth(child), this would mean depth decreases later, violating non-decreasing depth. So depth monotonic check catches that.
But what if parent and child are at same depth? Not possible in tree (except if there is an edge connecting nodes at same depth? In a tree, edges connect nodes whose depths differ by 1 if rooted at 1, because it's a tree, and we defined depth as distance from root. So no.
Thus algorithm stands.
Now we must implement efficiently.
Implementation steps:
- Read n.
- Build adjacency list (vector<vector> adj(n+1)).
- BFS from 1 to compute depth and parent.
- Use queue, visited array.
- Initialize depth[1]=0, parent[1]=0.
- For each neighbor, if not visited, set depth[neighbor]=depth[current]+1, parent[neighbor]=current, push.
(Since it's tree, no cycles, but visited prevents revisiting parent.)
- Read sequence a[1..n].
- Check a[1]==1.
- For i=2..n: if depth[a[i]] < depth[a[i-1]] or depth[a[i]] > depth[a[i-1]]+1: print No and exit.
Actually we need depth[a[i]] >= depth[a[i-1]] and depth[a[i]] <= depth[a[i-1]]+1.
- Compute max depth (maybe not needed). Prepare vector<vector> levels(maxDepth+1). Actually we can compute max depth during BFS.
- For i from 1 to n: levels[depth[a[i]]].push_back(a[i])? But careful: We need levels in order of appearance? Actually we need for each depth, the nodes in the order they appear in the sequence. So we can iterate over a (1..n) and push each node to levels[depth[node]].
However, note that if depth monotonicity holds, nodes of each depth will appear contiguously. But even if not, we may still build levels anyway; but if depth monotonicity fails we would have already rejected. So it's safe.
- For each depth d, for each node in that level, we need to assign orderInLevel. We'll create array orderInLevel[n+1]. For each depth d from 0 to maxDepth, iterate j from 0 to size-1, set orderInLevel[levels[d][j]] = j.
- For each depth d from 1 to maxDepth, iterate over nodes v in levels[d] in order:
- p = parent[v]
- if depth[p] != d-1: something wrong (should not happen).
- idx = orderInLevel[p]
- if idx < prev_idx (strictly less? Since non-decreasing, we require idx >= prev_idx). Set prev_idx = idx.
- If at any point idx < prev_idx, output No and exit.
- If all checks pass, output Yes.
Edge Cases:
-
Root has depth 0. No need to check level 0's parent.
-
If n==1, steps: depth[1]=0, a[1]=1, depth monotonicity (no loop), levels[0] = [1], orderInLevel[1]=0. For d from 1 to maxDepth (maxDepth=0), loop none. So Yes.
Complexities: O(n).
Now test with given examples.
Example 1:
n=4, edges: 1-2,1-3,2-4.
BFS: depth: 1:0,2:1,3:1,4:2.
Sequence: 1 2 3 4.
Check depth: 0,1,1,2 -> all non-decreasing and increments <=1.
levels: depth0:[1], depth1:[2,3], depth2:[4].
orderInLevel: 1:0; 2:0; 3:1.
Check depth1: prev = -inf; v=2 p=1 idx=0 => ok prev=0; v=3 p=1 idx=0? Actually parent of 3 is 1, idx=0. 0 >=0 -> ok (but note 3's parent is also 1, idx=0, so sequence of idx [0,0] non-decreasing). Depth2: v=4 p=2 idx=orderInLevel[2]=0. prev=0? Actually we start new level; prev initially -inf; v=4 idx=0 >= -inf, ok. So Yes.
Example 2:
Sequence: 1 2 4 3.
Depths: 0,1,2,1 -> depth[4]=2, depth[3]=1. At i=4, depth[3]=1, prev depth[4]=2 -> depth[3] < depth[4] -> fails monotonicity. So No.
Now test with our earlier valid order 1,2,3,5,4,6 for the tree described. Let's compute depths:
1:0
2:1
3:1
4:2
5:2
6:2
Sequence: [1,2,3,5,4,6] depths: 0,1,1,2,2,2 -> monotonic ok.
levels: d0:[1], d1:[2,3], d2:[5,4,6].
orderInLevel: d0: 1:0; d1:2:0,3:1.
Check d2: v=5 p=2 idx=0; v=4 p=2 idx=0 (0>=0); v=6 p=3 idx=1 (1>=0) -> non-decreasing. So Yes.
Now test an invalid order that passes monotonicity but fails parent indices. Example: 1,2,3,6,4