CF1037DValidBFS题解--优先队列BFS

题目链接

https://www.luogu.org/problemnew/show/CF1037D

分析

看上去好容易啊,直接将在排列中的位置当作权值赋给点一波优先队列BFS就好了,然后就WA了,其实就是

PQF大佬图片所说的这种情况https://www.luogu.org/blog/PQF/solution-cf1037d

然后解决方法其实很容易,再给每个点赋个BFS序作为第一关键字,权值为第二关键字就好了

不理解就看代码吧,其实一下就懂了

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Code By RyeCatcher
10.10
*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <vector>
#include <queue>
#include <utility>
#define ri register int
#define ll long long
#define ull unsigned long long
#define pb push_back
#define FO(x) {freopen(#x".in","r",stdin);freopen(#x".out","w",stdout);}
#define SIZE 233333
using std::min;
using std::max;
using std::pair;
using std::queue;
using std::priority_queue;
using std::vector;
inline char gc(){
static char buf[SIZE],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,SIZE,stdin),p1==p2)?EOF:*p1++;
}
template <class T>inline void read(T &x){
x=0;int ne=0;char c;
while((c=getchar())>'9'||c<'0')ne=c=='-';x=c-48;
while((c=getchar())>='0'&&c<='9')x=(x<<3)+(x<<1)+c-48;x=ne?-x:x;return ;
}
const int maxn=200005;
const int inf=0x7fffffff;
struct Edge{
int ne,to;
}edge[maxn<<1];
int h[maxn],num_edge=1;
inline void add_edge(int f,int to){
edge[++num_edge].ne=h[f];
edge[num_edge].to=to;
h[f]=num_edge;
}
struct Dat{
int val,ver,dfn;
Dat (){val=-inf,dfn=inf,ver=0;}
Dat (int _x,int _y,int _z){val=_x,ver=_y,dfn=_z;}
bool operator <(const Dat &b)const{
return dfn==b.dfn?val>b.val:dfn>b.dfn;
}
};
priority_queue <Dat> q;
int w[maxn],arr[maxn],st[maxn],top=0;
int n;
bool vis[maxn];
inline void bfs(){
int u,v,x;
int cnt=0;//BFS次序
memset(vis,0,sizeof(vis));
q.push(Dat(0,1,cnt));
vis[1]=1;
while(q.size()){
u=q.top().ver;
cnt++;
st[++top]=u;
q.pop();
for(ri i=h[u];i;i=edge[i].ne){
v=edge[i].to;
if(vis[v])continue;
vis[v]=1;
q.push(Dat(w[v],v,cnt));
}
}
return ;
}
int main(){
int x,y;
read(n);
for(ri i=1;i<n;i++){
read(x),read(y);
add_edge(x,y);
add_edge(y,x);
}
for(ri i=1;i<=n;i++){
read(arr[i]);
w[arr[i]]=i;
}
bfs();
for(ri i=1;i<=n;i++)if(arr[i]!=st[i]){
puts("No");exit(0);
}
puts("Yes");
return 0;
}