fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<vector<int>> adj;
  5. unordered_set<int> S;
  6. long long moves = 0;
  7.  
  8. bool dfs(int node, int parent) {
  9. bool has = (S.count(node) > 0);
  10.  
  11. for (int it : adj[node]) {
  12. if (it == parent) continue;
  13.  
  14. if (dfs(it, node)) {
  15. moves += 2;
  16. has = true;
  17. }
  18. }
  19. return has;
  20. }
  21.  
  22. int main() {
  23. ios::sync_with_stdio(false);
  24. cin.tie(nullptr);
  25.  
  26. int n, t;
  27. cin >> n >> t;
  28.  
  29. adj.resize(n + 1);
  30.  
  31. for (int i = 0; i < t; i++) {
  32. int x;
  33. cin >> x;
  34. S.insert(x);
  35. }
  36.  
  37. for (int i = 0; i < n - 1; i++) {
  38. int u, v;
  39. cin >> u >> v;
  40. adj[u].push_back(v);
  41. adj[v].push_back(u);
  42. }
  43.  
  44. dfs(1, 0);
  45. cout << moves << "\n";
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 5308KB
stdin
5 2
3 5
1 2
2 3
3 4
4 5
stdout
8