CF-div3-629-E - Tree Queries

Ideas analysis

Meaning of the questions: Let us find a chain tree, so that all points in the chain, or the distance from the point of this chain is 1;
analysis:
1. If the distance on this point to the chain 1, illustrate the point father in the chain.
2. The first thought to think about how to find this chain, certainly from the root to the deepest point of the depth of this chain, because the deeper end deep, the more this chain can cover the point thing.
3. Then as long as the father or other nodes judged to this point is not on one strand of it. Judgment is not in a chain, as long as the LCA determination (the current node, the deepest node) = the current node is not the current node or the father.

Method: Split Tree chain obtained lca, father, deep, and then find the deepest point, and other points it is determined whether the condition to lca.

Code

#include<bits/stdc++.h>
using namespace std;

const int maxn = 2e5+100;
vector<int> g[maxn];
int fa[maxn],depth[maxn],sz[maxn],son[maxn],id[maxn],rk[maxn],top[maxn],bot[maxn];
int cnt = 0;
int root;

void dfs(int x,int deep){
	depth[x] = deep;
	sz[x] = 1;
	for(int li = 0;li<g[x].size();li++){
		int i = g[x][li];
		if(i == fa[x]) continue;
		fa[i] = x;
		dfs(i,deep+1);
		sz[x] += sz[i];
		if(sz[i] > sz[son[x]]) son[x] = i;
	}
}

void dfs2(int x,int tp){
	top[x] = tp;
	id[x] = ++cnt;
	rk[cnt] = x;
	if(son[x]) dfs2(son[x],tp),bot[x] = bot[son[x]];
	else bot[x] = x;
	for(int li=0;li<g[x].size();li++){
		int i = g[x][li];
		if(i != fa[x] && i != son[x])
			dfs2(i,i);
	}
}

int lca(int u,int v){
	while(top[u] != top[v]){
		if(depth[top[u]] < depth[top[v]]) swap(u,v);
		u = fa[top[u]];
	}
	if(depth[u] < depth[v]) return u;
	return v;
}

int node[maxn];
void solve(){
	int k;
	cin>>k;
	int maxDeep = 0,maxNode;
	for(int i=1;i<=k;i++) {
		cin>>node[i];
		if(maxDeep <= depth[node[i]]){
			maxDeep = depth[node[i]];
			maxNode = node[i];
		}
	}
	for(int i=1;i<=k;i++){
		if(node[i] == maxNode) continue;
		int LCA = lca(maxNode,node[i]);
		if(!(LCA == node[i] || LCA == fa[node[i]])){
			puts("NO");
			return;
		}
	}
	puts("YES");
}

int main(){
	ios::sync_with_stdio(false);
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n-1;i++){
		int u,v;
		cin>>u>>v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	root = 1;
	dfs(root,1);
	dfs2(root,root);
	while(m--){
		solve();
	}
	return 0;
}

Guess you like

Origin www.cnblogs.com/fisherss/p/12580644.html