D. Valid BFS?
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
The BFS algorithm is defined as follows.
- Consider an undirected graph with vertices numbered from 11 to nn. Initialize qq as a new queue 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 tree is an undirected graph, such that there is exactly one simple path between any two vertices.
Input
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.
Output
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).
Examples
input
Copy
4 1 2 1 3 2 4 1 2 3 4
output
Copy
Yes
input
Copy
4 1 2 1 3 2 4 1 2 4 3
output
Copy
No
Note
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为根节点开始BFS能否跑出给定的序列?
题解:我们按照每个人的儿子在所给序列的顺序给他们排序,然后按照BFS的规则模拟即可。
#include<vector>
#include<queue>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
int dep[200005],n,a[200005],flag[200005],mark,id[200005];
vector<int>q[200005];
queue<int>qq;
bool comp(int x,int y)
{
if(id[x]<id[y])
return 1;
return 0;
}
int main(void)
{
int x,y;
scanf("%d",&n);
for(int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
q[x].push_back(y);
q[y].push_back(x);
}
for(int i=1;i<=n;i++)
scanf("%d",&a[i]),id[a[i]]=i;
for(int i=1;i<=n;i++)
sort(q[a[i]].begin(),q[a[i]].end(),comp);
qq.push(1);flag[1]=1; int cnt=1;
while(qq.empty()==0)
{
int tmp=qq.front();qq.pop();
if(a[cnt]!=tmp)
{
mark=1;
break;
}
for(int i=0;i<q[tmp].size();i++)
{
if(flag[q[tmp][i]]==0)
qq.push(q[tmp][i]),flag[q[tmp][i]]=1;
}
cnt++;
}
if(mark) printf("No\n");
else printf("Yes\n");
return 0;
}
/*
7
1 2
1 3
2 4
2 5
3 6
3 7
1 2 3 4 7 5 6
*/