[题目链接]
http://codeforces.com/problemset/problem/1037/D
[算法]
首先求出每个点的父节点 , 每棵子树的大小
然后判断BFS序是否合法即可
时间复杂度 : O(N)
[代码]
#include<bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 10; struct edge { int to , nxt; } e[MAXN << 1]; int n , tot; int a[MAXN],fa[MAXN],head[MAXN],size[MAXN]; template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); } template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); } template <typename T> inline void read(T &x) { T f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } inline void addedge(int u,int v) { tot++; e[tot] = (edge){v,head[u]}; head[u] = tot; } int main() { read(n); if (n == 1) { puts("YES"); return 0; } for (int i = 1; i < n; i++) { int u , v; read(u); read(v); addedge(u,v); addedge(v,u); } for (int i = 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()) { int u = q.front(); q.pop(); for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if (v != fa[u]) { size[u]++; fa[v] = u; q.push(v); } } } int t = 1 , cnt = 0; for (int i = 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 "); return 0; } cnt = 1; t++; continue; } printf("NO "); return 0; } if (cnt == size[a[t]]) printf("YES "); else printf("NO "); return 0; }