fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using i64 = long long;
  5.  
  6. const int inf=1e9;
  7.  
  8. void bfs(int u, vector<vector<int>> &g, vector<int> &dist, vector<bool> &p, vector<int> &a) {
  9. queue<int> q; q.push(u);
  10. dist[u] = 0;
  11. while (!q.empty()) {
  12. int node = q.front(); q.pop();
  13. if(p[node]) a.push_back(dist[node]);
  14. for (auto &x: g[node]) {
  15. if (dist[x] == -1) {
  16. dist[x] = dist[node] + 1;
  17. q.push(x);
  18. }
  19. }
  20. }
  21. }
  22.  
  23. void solve(){
  24. int n,k; cin>>n>>k;
  25.  
  26. vector<bool> p(n+1);
  27. for(int i=0;i<k;i++) {
  28. int x; cin>>x;
  29. p[x]=true;
  30. }
  31. int root=1;
  32. vector<vector<int>> g(n+1);
  33. vector<int> dist(n+1,-1),mset,ans(n+1);
  34.  
  35. for (int i = 0; i < n - 1; ++i) {
  36. int u, v; cin >> u >> v;
  37. g[u].push_back(v);
  38. g[v].push_back(u);
  39. }
  40. for (int i = 1; i <= n; ++i)
  41. if (g[i].size() == 1)
  42. root=i;
  43.  
  44. bfs(root, g, dist, p, mset);
  45. sort(mset.begin(), mset.end());
  46.  
  47. for (int i = 1; i <= n; ++i)
  48. ans[i] = max(abs(dist[i] - mset.front()), abs(dist[i] - mset.back()));
  49.  
  50. cout << *min_element(ans.begin()+1,ans.end())<<'\n';
  51. return;
  52. }
  53.  
  54. signed main() {
  55. ios::sync_with_stdio(false);
  56. cin.tie(nullptr); cout.tie(nullptr);
  57.  
  58. int t; cin>>t;
  59. while(t--){
  60. solve();
  61. }
  62. }
Runtime error #stdin #stdout 0.01s 5352KB
stdin
Standard input is empty
stdout
Standard output is empty