meeting

链接:https://ac.nowcoder.com/acm/contest/884/A
来源:牛客网

题目描述

A new city has just been built. There're  nnn interesting places numbered by positive numbers from 111 to nnn.
In order to save resources, only exactly  n−1n-1n1 roads are built to connect these nnn interesting places. Each road connects two places and it takes 1 second to travel between the endpoints of any road.
There is one person in each of the places numbered x1,x2…xkx_1,x_2 \ldots x_kx1,x2xk and they've decided to meet at one place to have a meal. They wonder what's the minimal time needed for them to meet in such a place. (The time required is the maximum time for each person to get to that place.)

输入描述:

First line two positive integers,  n,kn,kn,k - the number of places and persons.
For each the following  n−1n-1n1 lines, there're two integers a,ba,ba,b that stand for a road connecting place aaa and bbb. It's guaranteed that these roads connected all nnn places.
On the following line there're  kkk different positive integers x1,x2…xkx_1,x_2 \ldots x_kx1,x2xk separated by spaces. These are the numbers of places the persons are at.

输出描述:

A non-negative integer - the minimal time for persons to meet together.
示例1

输入

复制
4 2
1 2
3 1
3 4
2 4

输出

复制
2

说明

They can meet at place 1 or 3.

备注:

1≤n≤1051 \leq n \leq 10^51n105
#include<iostream>
#include<cstdio>
#include<cstring>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
int n,k,tot,head[maxn];
struct node{
    int to,nx;
}p[maxn];
void add_edge(int u,int v){
    p[++tot].to=v;
    p[tot].nx=head[u];
    head[u]=tot;
}
int x[maxn];
ll ans=0x3f3f3f3f;
int dis[maxn],e[maxn];
int vis[maxn];
int bfs(int s){
    queue<int>q;
    memset(vis,0,sizeof(vis));
    memset(dis,0x3f3f3f3f,sizeof(dis));
    dis[s]=0;
    vis[s]=1;
    q.push(s);
    ll tmp=0,nd=s;
    while(!q.empty()){
        int cur=q.front();
        q.pop();
        //vis[cur]=0;
        if(dis[cur]>tmp&&e[cur]){
            tmp=dis[cur];
            nd=cur;
        }
        for(int i=head[cur];i;i=p[i].nx){
            int to=p[i].to;
            if(!vis[to]){
                vis[to]=1;
                q.push(to);
                dis[to]=dis[cur]+1;
            }
        }
    }
    return nd;
}
int main(){
    cin>>n>>k;
    for(register int i=1,u,v;i<n;++i){
        scanf("%d%d",&u,&v);
        add_edge(u,v);
        add_edge(v,u);
    }
    for(register int i=1;i<=k;++i){
        scanf("%d",&x[i]);
        e[x[i]]=1;
    }
    ans=ceil(dis[bfs(bfs(x[1]))]/2.0);
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/czy-power/p/11256145.html