链接:https://ac.nowcoder.com/acm/contest/884/A
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld
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-1n−1 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,x2…xk 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-1n−1 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,x2…xk 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^51≤n≤105
树形dp,把定点1当成树根,进行两次dp,第一次获得这个点下面的点中的人到这个点的最长路径,第二次获得这个点上面点中的人到这个点最长路径就好了。
#include
#include
#include
#include
#include
using namespace std;
int n, m;
const int maxn = 100005;
vectorG[100005];
int dp[maxn]; int pos[maxn];
int ans[maxn]; int real_ans = 0x3f3f3f3f;
void dfs1(int u, int fa) {
int res = dp[u];
for (auto v : G[u]) {
if (v == fa)continue;
dfs1(v, u);
res = max(res, pos[v] + 1);
}
pos[u] = res;
}
void dfs2(int u, int fa,int sum) {
ans[u] = max(sum, pos[u]);
// cout << u << " " << ans[u] << "\n";
real_ans = min(real_ans, ans[u]);
int tmax = -0x3f3f3f3f, tnum;
int tmax2 = -0x3f3f3f3f;
int tsum = 0;
for (auto v : G[u]) {
if (v == fa)continue;
tsum++;
if (tmax < pos[v]) {
tmax = pos[v];
tnum = v;
}
}
for (auto v : G[u]) {
if (v == fa)continue;
if (v == tnum)continue;
if (tmax2 < pos[v]) {
tmax2 = pos[v];
}
}
for (auto v : G[u]) {
if (v == fa)continue;
if (v == tnum)continue;
dfs2(v, u, max(tmax + 2, sum + 1));
}
if (tsum != 0)
dfs2(tnum, u, max(tmax2 + 2, sum + 1));
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
while (cin >> n >> m) {
for (int i = 1; i <= n; i++) {
dp[i] = -0x3f3f3f;
}
for (int i = 1; i < n; i++) {
int a, b; cin >> a >> b;
G[a].push_back(b);
G[b].push_back(a);
}
for (int i = 0; i < m; i++) {
int a; cin >> a;
dp[a] = 0;
}
dfs1(1, 1);
dfs2(1, 1, -0x3f3f3f);
cout << real_ans << "\n";
}
return 0;
}
/*
6 6
1 2
2 3
2 4
2 5
5 6
1 2 3 4 5 6
*/