题目
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
vector<vector<int>> g;
bool st[N];
int ans = 1e9;
bool dfs(int f, int u, int dis)
{bool is = 1;for (auto j : g[u]){if (j == f)continue;is &= dfs(u, j, dis + (g[u].size() > 2));}if (g[u].size() == 1) // 无向图叶子节点判定is = st[u];if (is)ans = min(ans, dis);return is;
}
int main()
{int n;cin >> n;g.resize(n + 1);for (int i = 1; i < n; i++){int a, b;cin >> a >> b;g[a].push_back(b);g[b].push_back(a);}g[1].push_back(-1); // 为了统一那个多出来的父节点int m;cin >> m;for (int i = 1; i <= m; i++){int x;cin >> x;st[x] = 1;}dfs(-1, 1, 0);cout << ans;return 0;
}