1328E - Tree Queries(思维+LCA)

https://codeforces.com/problemset/problem/1328/E


给出一棵以点 1 为根节点的树,接下来有 m 次询问,每次询问给出 k 个点,题目问我们能否找到一个点 u ,使得从根节点到点 u 的简单路径,到 k 个点的每个点的距离都小于等于 1 

思路:

开始想着k个点两两暴力匹配找lca..但是实际上找最深的一个来匹配就行了。然后看其他的点和他的lca是否距离>1

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
vector<LL>g[maxn];
vector<LL>v;
LL dep[maxn],siz[maxn],son[maxn],fat[maxn],tot=0;
LL top[maxn];
void predfs(LL u,LL fa){
    siz[u]=1;
    dep[u]=dep[fa]+1;
    fat[u]=fa;
    for(int i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==fa) continue;
        predfs(v,u);
        siz[u]+=siz[v];
        if(siz[v]>siz[son[u]]){
            son[u]=v;
        }
    }
}
void dfs(LL u,LL topx){
    top[u]=topx;
    if(son[u]==0) return;
    dfs(son[u],topx);
    for(int i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==fat[u]||v==son[u]) continue;
        dfs(v,v);
    }
}
LL lca(LL u,LL v){
   while(top[u]!=top[v]){
      if(dep[top[u]]<dep[top[v]]) swap(u,v);
      u=fat[top[u]];
   }
   return dep[u]<dep[v]?u:v;
}
int main(void){

     LL n,m;n=read();m=read();
     for(int i=1;i<n;i++){
        LL u,v;u=read();v=read();
        g[u].push_back(v);
        g[v].push_back(u);
     }
     predfs(1,0);
     dfs(1,1);
     while(m--){
        LL k;k=read();
        LL mx=0;LL num=0;
        v.clear();
        for(int j=1;j<=k;j++){
            LL x;x=read();
            v.push_back(x);
            if(mx<dep[x]){
                mx=dep[x];num=x;
            }
        }

        bool flag=1;
        for(int j=0;j<v.size();j++){
            LL LCA=lca(v[j],num);
            if(min(dep[v[j]],dep[num])-dep[LCA]>1){
                flag=0;break;
            }
        }
        if(flag) printf("YES\n");
        else printf("NO\n");
     }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/115364859
今日推荐