题意:选一点使k个关键点到这一点的最长路径长度最小,输出最长路径
题解:
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int maxn= 1e5+5;
const ll INFF =1e18;
const int INF =1e9;
int n,k;
struct node{
int x,step;
};
vector<int>G[maxn];
set<int>se;
int vis[maxn];
int bfs(int s){
memset(vis,0,sizeof(vis));
queue<int>q;
q.push(s);vis[s]=1;
int last;
while(!q.empty()){
int u=q.front();q.pop();
if(se.find(u)!=se.end())
last=u;
for(int i=0;i<G[u].size();i++){
int v=G[u][i];
if(!vis[v]){
vis[v]=1;
q.push(v);
}
}
}
return last;
}
int bfs2(int s){
memset(vis,0,sizeof(vis));
node now,next;
queue<node>q;vis[s]=1;
now.x=s;now.step=0;
int last;
q.push(now);
while(!q.empty()){
//cout<<now.x<<endl;
now=q.front();q.pop();
if(se.find(now.x)!=se.end())
last=now.step;
for(int i=0;i<G[now.x].size();i++){
int v=G[now.x][i];
next.x=v;next.step=now.step+1;
if(!vis[next.x]){
vis[next.x]=1;
q.push(next);
}
}
}
return last;
}
int main()
{
scanf("%d%d",&n,&k);
for(int i=0;i<n-1;i++){
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=0;i<k;i++){
int tmp;
scanf("%d",&tmp);
se.insert(tmp);
}
int s=bfs(1);
int ans=bfs2(s);
cout<<(ans+1)/2<<endl;
}