E1. Escape The Maze (easy version)
我们显然遍历根节点到叶结点的同时维护最短距离
然后在return的时候看该点距离是否大于最近的朋友的距离
要是大于的话 我们显然可以走过去 否则我们把这条路叉掉
最后看他能不能到达一个根节点即可
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
const int M = 998244353;
const int mod = 1e9+7;
#define int long long
int up(int a,int b){return a<0?a/b:(a+b-1)/b;}
#define endl '\n'
#define all(x) (x).begin(),(x).end()
#define YES cout<<"YES"<<endl;
#define NO cout<<"NO"<<endl;
#define _ 0
#define pi acos(-1)
#define INF 0x3f3f3f3f3f3f3f3f
#define fast ios::sync_with_stdio(false);cin.tie(nullptr);
bool st[N],is[N];
int d[N];
vector<int>g[N];
int n,k;
int dfs(int u,int fa){
int res=INF;
if(d[u]>=res||is[u])st[u]=1;
for(auto v:g[u]){
if(v==fa)continue;
d[v]=d[u]+1;
int t=dfs(v,u);
res=min(res,t);
}
return (is[u]?1:res+1);
}
bool dfs2(int u,int fa){
for(auto v:g[u]){
if(st[v])continue;
if(v==fa)continue;
if(g[v].size()==1)return 1;
if(dfs2(v,u))return 1;
}
return 0;
}
void solve(){
cin>>n>>k;
for(int i=1;i<=n;i++)d[i]=st[i]=is[i]=0,g[i].clear();
for(int i=1;i<=k;i++){
int x;cin>>x;
is[x]=1;
}
for(int i=1;i<n;i++){
int u,v;cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1,0);
puts(dfs2(1,0)?"YES":"NO");
}
signed main(){
fast
int t;t=1;cin>>t;
while(t--) {
solve();
}
return ~~(0^_^0);
}
标签:return,dfs2,int,res,Codeforces,dfs,fa,Div,E1
From: https://www.cnblogs.com/ycllz/p/16814922.html