题目
题目大意
给你一堆双向边,保证能够形成一个树,再给你一个一个序列,问你这个序列和给出的边形成的树一样不?
题目链接
题解
刚开始想的是先bfs,然后计算出下一层的儿子的位置在哪,然后这个这么太难写了,所以瞅了眼题解重新写一下。思路是把bfs的顺序重新排列下,按照给出的序列的下标重新排列。然后再bfs一下就行,然后判断bfs出来的和给出来的有什么不一样吗,一样的yes,不一样no
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <bitset>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#define x first
#define y second
#define endl '\n'
#define IOS \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f, mod = 1000000007;
const int N = 2e5 + 10;
int n;
int b[N];
vector<int> a[N], ans;
map<int, int> pos, vis;
bool cmp(int a, int b) {
return pos[a] < pos[b];
}
void solve() {
cin >> n;
for(int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
a[x].push_back(y);
a[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
pos[b[i]] = i;
}
for(int i = 1; i <= n; i++)
sort(a[i].begin(), a[i].end(), cmp);
queue<int> q;
q.push(1);
ans.push_back(1);
vis[1] = 1;
while(q.size()) {
auto t = q.front();
q.pop();
for(auto x : a[t]) {
if(!vis[x]) {
vis[x] = 1;
q.push(x);
ans.push_back(x);
}
}
}
for(int i = 0; i < n; i++) {
if(b[i + 1] != ans[i]) {
cout << "No\n";
return;
}
}
cout << "Yes\n";
}
int main()
{
// IOS;
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
}