原题链接
51nod 2666
题目类型:
5
5
5级题
♦
♦
♦
♦
♦
{\color{green}{♦♦}}{\color{lightgreen}{♦♦}}{\color{yellow}{♦}}{\color{orange}{}}{\color{red}{}}
♦♦♦♦♦
AC记录:Accepted
题目大意
给定一棵 n n n个点的有根树,根为 1 1 1号点。再给一个序列 a a a,请你回答这个序列是不是这棵树的合法 B F S BFS BFS序
输入格式
输入第一行一个整数
n
n
n,表示树的节点数。
接下来
n
−
1
n-1
n−1行表示这棵树的结构,每行一对
u
,
v
u,v
u,v,表示
u
,
v
u,v
u,v两点间有一条连边。
接下来一行共
n
n
n个数,表示
a
1
,
a
2
,
⋯
,
a
n
a_1,a_2,\cdots,a_n
a1,a2,⋯,an。
输出格式
输出仅一行,一个字符串Yes
或No
,表示是否为合法
B
F
S
BFS
BFS序列。
S
a
m
p
l
e
\mathbf{Sample}
Sample
I
n
p
u
t
\mathbf{Input}
Input
4
1 2
1 3
2 4
1 2 3 4
S a m p l e \mathbf{Sample} Sample O u t p u t \mathbf{Output} Output
Yes
H
i
n
t
&
E
x
p
l
a
i
n
\mathbf{Hint\&Explain}
Hint&Explain
样例所示的树如下图所示,可以知道1 2 3 4
为这棵树的一组
B
F
S
BFS
BFS序。
数据范围
对于 100 % 100\% 100%的数据, 1 ≤ n ≤ 2 × 1 0 5 , 1 ≤ u , v , a i ≤ n 1\le n\le 2\times 10^5,1\le u,v,a_i\le n 1≤n≤2×105,1≤u,v,ai≤n。
解题思路
此题可以用
b
f
s
bfs
bfs来解决。
由于题目说了
1
1
1号节点为根,所以我们可以从
1
1
1号节点开始用
b
f
s
bfs
bfs拓展,再记录一个vector
数组
r
o
a
d
i
road_i
roadi,记录有多少个节点可以和
i
i
i节点相连,最后,再按照给出的
b
f
s
bfs
bfs序列来开始扩展,记录下每一个节点会在什么时候出现,判断和原来给出的序列是否一样就可以了。
注意事项:
1.在排序的时候要记得按照题目中给出序列从左到右排序。
2.在建立边的时候记得要建双向边!即a->b
和b->a
两条边。
最后,祝大家早日
上代码
#include<bits/stdc++.h>
using namespace std;
vector<int> road[200010];
queue<int> q;
bool vis[200010];
int bfs[200010];
int base[200010];
int n,pos;
inline bool pd(int x,int y)
{
return base[x]<base[y];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for(int i=1; i<n; i++)
{
int x,y;
cin>>x>>y;
road[x].push_back(y);
road[y].push_back(x);
}
for(int i=1; i<=n; i++)
{
int x;
cin>>x;
base[x]=i;
}
for(int i=1; i<=n; i++)
sort(&road[i][0],&road[i][road[i].size()],pd);
q.push(1);
vis[1]=true;
while(q.size())
{
int now=q.front();
q.pop();
bfs[now]=++pos;
for(int i=0; i<road[now].size(); i++)
{
if(!vis[road[now][i]])
{
vis[road[now][i]]=true;
q.push(road[now][i]);
}
}
}
for(int i=1; i<=n; i++)
{
if(bfs[i]!=base[i])
{
cout<<"No"<<endl;
return 0;
}
}
cout<<"Yes"<<endl;
return 0;
}
完美切题 ∼ \sim ∼