The algorithm is defined as follows.
- Consider an undirected graph with vertices numbered from 11 to nn. Initialize qq as a new containing only vertex 11, mark the vertex 11 as used.
- Extract a vertex vv from the head of the queue qq.
- Print the index of vertex vv.
- Iterate in arbitrary order through all such vertices uu that uu is a neighbor of vv and is not marked yet as used. Mark the vertex uu as used and insert it into the tail of the queue qq.
- If the queue is not empty, continue from step 2.
- Otherwise finish.
Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.
In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 11. The is an undirected graph, such that there is exactly one simple path between any two vertices.
The first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) which denotes the number of nodes in the tree.
The following n−1n−1 lines describe the edges of the tree. Each of them contains two integers xx and yy (1≤x,y≤n1≤x,y≤n) — the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree.
The last line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n) — the sequence to check.
Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise.
You can print each letter in any case (upper or lower).
4 1 2 1 3 2 4 1 2 3 4
Yes
4 1 2 1 3 2 4 1 2 4 3
No
Both sample tests have the same tree in them.
In this tree, there are two valid BFS orderings:
- 1,2,3,41,2,3,4,
- 1,3,2,41,3,2,4.
The ordering 1,2,4,31,2,4,3 doesn't correspond to any valid BFS order.
分析:根据题意,进行第一个样例的模拟,我们可以发现,既然1一定是第一个数,就从1开始扩展,它连接2,3,那么后面一定是2,3,所以需要扫描2,3位置,然后2连接4,扫描4位置
我们可以发现即使有很多数,扫描过程也是从前往后线性进行的,所以可以直接根据题意进行模拟,先标记该位置连接的数,再扫描具体的区间看是否相符。
代码如下:
#include#include #include #include #include using namespace std;#define INF 0x3f3f3f3fconst int MAXN=2e5+100;int n,x,y;vector V[MAXN];int vis[MAXN];int a[MAXN];int main(){ scanf("%d",&n); for(int i=1;i<=n-1;i++) { scanf("%d%d",&x,&y); V[x].push_back(y); V[y].push_back(x); } for(int i=1;i<=n;i++) scanf("%d",&a[i]); vis[1]=1; int p=2; bool flag=true; if(a[1]!=1) flag=false; int len=V[a[1]].size(); for(int i=1;i<=n;i++) { for(int j=0;j