D. Valid BFS?
http://codeforces.com/contest/1037/problem/D
题意:
给一个序列,一棵树,判断能否bfs这棵树,得到这个序列。
分析:
将每个点所达到的点,按照序列中出现的位置排序,然后bfs,判断是否相等。
代码:
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #include<cmath> 5 #include<iostream> 6 #include<cctype> 7 #include<set> 8 #include<vector> 9 #include<queue> 10 #include<map> 11 #define fi(s) freopen(s,"r",stdin); 12 #define fo(s) freopen(s,"w",stdout); 13 using namespace std; 14 typedef long long LL; 15 16 inline int read() { 17 int x=0,f=1;char ch=getchar();for(;!isdigit(ch);ch=getchar())if(ch=='-')f=-1; 18 for(;isdigit(ch);ch=getchar())x=x*10+ch-'0';return x*f; 19 } 20 21 const int N = 200005; 22 23 int a[N], q[N], b[N], pos[N]; 24 vector<int> T[N]; 25 bool vis[N]; 26 27 bool cmp(int i,int j) { 28 return pos[i] < pos[j]; 29 } 30 31 int main() { 32 int n = read(); 33 for (int i=1; i<n; ++i) { 34 int u = read(), v = read(); 35 T[u].push_back(v), T[v].push_back(u); 36 } 37 for (int i=1; i<=n; ++i) a[i] = read(), pos[a[i]] = i; 38 for (int i=1; i<=n; ++i) 39 sort(T[i].begin(), T[i].end(), cmp); 40 int L = 1, R = 0, tot = 0; 41 q[++R] = 1; 42 while (L <= R) { 43 int u = q[L ++]; 44 b[++tot] = u; 45 vis[u] = true; 46 for (int sz=T[u].size(),i=0; i<sz; ++i) { 47 int v = T[u][i]; 48 if (vis[v]) continue; 49 q[++R] = v; 50 } 51 } 52 for (int i=1; i<=n; ++i) { 53 if (a[i] != b[i]) { 54 puts("No"); return 0; 55 } 56 } 57 puts("Yes"); 58 return 0; 59 }