Codeforces Round #629 (Div. 3) Editorial E. Tree Queries

讲解:https://blog.csdn.net/qq_45458915/article/details/105132814

#include
#include
#include
#include
#include
using namespace std;
#define ll long long
const int inf=0x3f3f3f3f;
const int N=2e5+100;
vector<int>node[N];
int fa[N],in[N],out[N],deep[N],cnt;
int k,max_deep,a[N];
void dfs(int u,int f,int dep)
{
	fa[u]=f;
	deep[u]=dep;
	in[u]=++cnt;
	for(int i=0;i<node[u].size() ;i++)
	{
		int v=node[u][i];
		if(v==f) continue;
		dfs(v,u,dep+1);
	}
	out[u]=++cnt;
}
bool check(int a,int b)
{
	return in[a]<=in[b]&&out[b]<=out[a];
}
bool solve()
{
	for(int i=1;i<=k;i++)
	{
		if(!check(a[i],max_deep)&&!check(fa[a[i]],max_deep))
		return 0;
	}
	return 1;
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<n;i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		node[u].push_back(v);
		node[v].push_back(u);
	}
	dfs(1,-1,0);
	while(m--)
	{
		scanf("%d",&k);
		max_deep=0;
		for(int i=1;i<=k;i++)
		{
			scanf("%d",&a[i]);
			if(max_deep==0||deep[max_deep]<deep[a[i]])
			max_deep=a[i];
		}
		if(solve()) printf("YES\n");
		else printf("NO\n");
	}
	//for(int i=1;i<=n;i++) printf("%d %d\n",in[i],out[i]);
}

你可能感兴趣的:(dfs序)