题意:给你一颗树(无向图),问你是否满足BFS序?
分析:用dfs把树隔离出来,然后bfs去遍历,看是否满足;由于兄弟节点顺序可能不一致,用set查找。
#include <bits/stdc++.h>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
#define met(s) memset(s, 0, sizeof(s))
#define rep(i, a, b) for(int i = a; i < b; ++i)
template <class T> inline void scan_d(T &ret) {
char c; ret = 0;
while ((c = getchar()) < '0' || c > '9');
while (c >= '0' && c <= '9') {
ret = ret * 10 + (c - '0'), c = getchar();}}
typedef long long LL;
#define asdf(a) ((int)a.size())
const int MOD = (int)1e9 + 7;
const int MAXN = (int)2e5 + 5;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
int vis[MAXN];
vector<int> V[MAXN];
set<int> s[MAXN];
void dfs(int v, int fa) {
for(int i = 0; i < V[v].size(); ++i) {
int u = V[v][i];
if(u != fa) {
s[v].insert(u);
dfs(u, v);
}
}
}
int main() {
int n, x, y;
scanf("%d", &n);
for(int i = 1; i < n; ++i) {
scanf("%d%d", &x, &y);
V[x].push_back(y);
V[y].push_back(x);
}
dfs(1, 0);
scanf("%d", &x);
if(x != 1) {
puts("No");
return 0;
}
queue<int> que;
que.push(x);
bool flag = true;
while(!que.empty()) {
int cnt = que.front();
que.pop();
for(int i = 0; i < s[cnt].size(); ++i) {
scanf("%d", &x);
if(s[cnt].find(x) == s[cnt].end() || vis[x]) flag = false;
if(!flag) break;
vis[x] = 1;
que.push(x);
}
if(!flag) break;
}
if(flag) puts("Yes");
else puts("No");
return 0;
}