标签:bfs cst name describe https between you dfs strong
The BFS algorithm is defined as follows.
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 tree is an undirected graph, such that there is exactly one simple path between any two vertices.
The first line contains a single integer n (1≤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 x and y(1≤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 n distinct integers a1,a2,…,an (1≤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:
The ordering 1,2,4,3doesn‘t correspond to any valid BFS order.
给你一棵树以及一个序列,判断该序列是否为这棵树的一个合法BFS序。
BFS序的特征是会先列举出同一层的所有点,同时下一层的子结点要按照上一层的顺序列出。利用这个性质就可以接着道题了。记录每个点的儿子个数son[i],一个点的同一层的子节点必然在连续一段,长度为son[i]。每检查完一段就跳到当前父节点的下一个节点。
#include <iostream>
#include <cstdio>
#include <queue>
#define N 200002
using namespace std;
int head[N],ver[N*2],nxt[N*2],l;
int n,i,j,k,son[N],fa[N],a[N];
int read()
{
char c=getchar();
int w=0;
while(c<'0'||c>'9') c=getchar();
while(c<='9'&&c>='0'){
w=w*10+c-'0';
c=getchar();
}
return w;
}
void insert(int x,int y)
{
l++;
ver[l]=y;
nxt[l]=head[x];
head[x]=l;
}
void dfs(int x,int pre)
{
fa[x]=pre;
for(int i=head[x];i;i=nxt[i]){
int y=ver[i];
if(y!=pre){
son[x]++;
dfs(y,x);
}
}
}
int main()
{
n=read();
for(i=1;i<n;i++){
int u=read(),v=read();
insert(u,v);
insert(v,u);
}
for(i=1;i<=n;i++) a[i]=read();
dfs(1,0);
son[0]=1;
for(i=j=1;i<=n;i++,j++){
if(fa[a[i]]!=a[k]){
puts("No");
return 0;
}
if(j==son[a[k]]){
j=0;
k++;
while(son[a[k]]==0) k++;
}
}
puts("Yes");
return 0;
}
标签:bfs cst name describe https between you dfs strong
原文地址:https://www.cnblogs.com/LSlzf/p/11674861.html