题目描述
In 2019 ICPC subregions structure was changed a little. Now for each subregion, we need to choose the best place for the subregion finals. To make things fair we want to choose a city in such a way that all teams will spend the same amount of time to get there.
To make things simpler we say that all teams will use trains to get to the finals. The railroad system can be represented as a tree where each city is a vertex and some pairs of cities are connected by a railroad.
It takes exactly one hour to get from one city to another if they are directly connected.
You are given a description of the railroad system and the cities where teams are located. You need to choose any city that has an equal distance to all teams’ cities or detect that no such city exists.
输入
The first line of the input contains two integers n and m — the number of cities and the number of teams (1 ≤ m ≤ n ≤ 2 · 105). Each of the following n − 1 lines contains two integers vi and ui — the
indices of the cities connected by the i-th railroad (1 ≤ vi, ui ≤ n). It is guaranteed that for each pair of cities there is exactly one simple path connecting them.
The next line contains m integers c1, c2,…, cm — the cities of the teams (1 ≤ ci ≤ n). All teams are located in different cities.
输出
If it is impossible to choose a city fairly, output a single word “NO”. Otherwise, output a the word “YES” at the first line. The second line should contain a single integer — the city where subregion finals should be held. If there is more than one solution, output any of them.
样例输入 Copy
【样例1】
6 3
1 2
2 3
3 4
4 5
4 6
1 5 6
【样例2】
2 2
1 2
1 2
样例输出 Copy
【样例1】
YES
3
【样例2】
NO
题目大意:
给出一棵 n 个点的树,再给出 m 个关键点,(边权值都为1),问是否存在着一个点到 m 个关键点的距离都相同,存在的话输出任意一个即可
题目分析:
将这m个做源点,bfs 按层展开维护贡献,同时记录一下每个点在同一层最多被多少个关键点覆盖。
#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const int maxn=2e5+7;
int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+ch-'0';
ch=getchar();
}
return x*f;
}
int n,m,deep[maxn],num[maxn];
bool vis[maxn];
vector<int>a[maxn];
void bfs(){
queue<int>q;
for(int i=1;i<=n;i++){
if(vis[i]){
q.push(i);
deep[i]=num[i]=1;
}
}
while(!q.empty()){
int x=q.front(); q.pop();
for(int i=0;i<a[x].size();i++){
int y=a[x][i];
if(deep[y]==0||deep[y]==deep[x]+1){
num[y]+=num[x];
if(!vis[y]){
vis[y]=1;
deep[y]=deep[x]+1;
q.push(y);
}
}
}
}
}
int main(){
n=read(); m=read();
for(int i=1;i<n;i++){
int x,y;
x=read(); y=read();
a[x].push_back(y); a[y].push_back(x);
}
for(int i=0;i<m;i++){ int x; x=read(); vis[x]=1; }
bfs();
for(int i=1;i<=n;i++){
if(num[i]==m){
printf("YES\n%d",i);
return 0;
}
}
printf("NO");
}