[题解] [CF1037D] Valid BFS?

题面

题解

一个是模拟BFS的过程

还有一个是可以根据给出的BFS序构树, 再看两棵树是否相同

判断相同的话, 以同一个点为根, 看两棵树中1−𝑛的点的𝑓𝑎是否都相同

代码

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#define N 200005
using namespace std;

int n, head[N], f[N][2], son[N], a[N], mx, cnt, pos; 
struct edge { int to, next, cost; } e[N << 1]; 
bool vis[N]; 

template < typename T >
inline T read()
{
	T x = 0, w = 1; char c = getchar();
	while(c < '0' || c > '9') { if(c == '-') w = -1; c = getchar(); }
	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return x * w; 
}

inline void adde(int u, int v) { e[++cnt] = (edge) { v, head[u] }; head[u] = cnt; }

void dfs(int u, int fa, int opt = 0)
{
	f[u][opt] = fa;
	for(int v, i = head[u]; i; i = e[i].next)
	{
		v = e[i].to; if(v == fa) continue;
		son[u]++; dfs(v, u, opt); 
	}
}

void bfs()
{
	queue<int> q;
	q.push(a[++pos]);
	while(!q.empty())
	{
		int u = q.front(); q.pop(); 
		for(int i = pos + 1; i <= pos + son[u]; i++)
		{
			adde(u, a[i]), adde(a[i], u); 
			q.push(a[i]); 
		}
		pos = pos + son[u]; 
	}
}

int main()
{
	n = read <int> ();
	for(int u, v, i = 1; i < n; i++)
		u = read <int> (), v = read <int> (), adde(u, v), adde(v, u); 
	dfs(1, 0);
	memset(head, 0, sizeof(head)), cnt = 0;
	for(int i = 1; i <= n; i++)
		a[i] = read <int> ();
	bfs(); 
	dfs(1, 0, 1);
	for(int i = 1; i <= n; i++)
		if(f[i][0] != f[i][1]) { puts("No"); return 0; }
	puts("Yes"); 
	return 0; 
}
posted @ 2019-11-06 17:23  ztlztl  阅读(89)  评论(0编辑  收藏  举报