[Topic link]
Http://codeforces.com/problemset/problem/1037/D
Algorithm
First find the parent node of each point, the size of each subtrees tree
Then determine whether the BFS sequence is legal
Time complexity: O (N)
Code
#include <bits/stdc++.h>using namespacestd;Const intMAXN = 2e5 +Ten;structedge{intto, NXT;} E[MAXN<<1];intn, tot;inta[maxn],fa[maxn],head[maxn],size[maxn];template<typename t> InlinevoidChkmax (T &x,t y) {x =Max (x, y);} Template<typename t> InlinevoidChkmin (T &x,t y) {x =min (x, y);} Template<typename t> InlinevoidRead (T &x) {T F=1; x =0; Charc =GetChar (); for(;!isdigit (c); c = GetChar ())if(c = ='-') F =-F; for(; IsDigit (c); c = GetChar ()) x = (x <<3) + (x <<1) + C-'0'; X*=F;} InlinevoidAddedge (intUintv) {Tot++; E[tot]=(Edge) {V,head[u]}; Head[u]=tot;}intMain () {read (n); if(n = =1) {puts ("YES");return 0; } for(inti =1; I < n; i++) { intu, v; Read (u); Read (v); Addedge (U,V); Addedge (V,u); } for(inti =1; I <= N; i++) read (A[i]); if(a[1] !=1) {puts ("NO");return 0; } Queue<int>Q; fa[1] = -1; Q.push (1); while(!Q.empty ()) { intU =Q.front (); Q.pop (); for(inti = Head[u]; I i =e[i].nxt) { intv =e[i].to; if(V! =Fa[u]) {Size[u]++; FA[V]=u; Q.push (v); } } } intt =1, cnt =0; for(inti =2; I <= N; i++) { if(Fa[a[i]] = =A[t]) {CNT++; Continue; } if(CNT = =Size[a[t]]) { while(T < i && size[a[t +1]] ==0) t++; if(T = =i) {printf ("no\n"); return 0; } CNT=1; T++; Continue; } printf ("no\n"); return 0; } if(cnt = = Size[a[t]]) printf ("yes\n"); Elseprintf"no\n"); return 0; }
[Codeforces 1037D] Valid BFS?