標籤:pen force main ++ 時間 inline dig == style
[題目連結]
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\n"); return 0; } cnt = 1; t++; continue; } printf("NO\n"); return 0; } if (cnt == size[a[t]]) printf("YES\n"); else printf("NO\n"); return 0; }
[Codeforces 1037D] Valid BFS?