fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n = 8;
  6. vector<int> targets = {5, 6};
  7. vector<pair<int, int>> edges = {
  8. {1, 2}, {2, 5}, {2, 3}, {2, 6},
  9. {1, 4}, {4, 7}, {7, 8}
  10. };
  11.  
  12. // build graph
  13. vector<vector<int>> g(n + 1);
  14. for (auto [u, v] : edges) {
  15. g[u].push_back(v);
  16. g[v].push_back(u);
  17. }
  18.  
  19. // bfs from root to get parent pointers
  20. vector<int> par(n + 1, -1);
  21. queue<int> q;
  22. q.push(1);
  23. par[1] = 0;
  24.  
  25. while (!q.empty()) {
  26. int u = q.front();
  27. q.pop();
  28. for (int v : g[u]) {
  29. if (par[v] == -1) {
  30. par[v] = u;
  31. q.push(v);
  32. }
  33. }
  34. }
  35.  
  36. // walk up from each target to root, collecting all intermediate nodes
  37. set<int> nodes;
  38. nodes.insert(1);
  39.  
  40. for (int t : targets) {
  41. nodes.insert(t);
  42. while (t != 1 && t != 0) {
  43. t = par[t];
  44. nodes.insert(t);
  45. }
  46. }
  47.  
  48. // if there's just one node, we don't move
  49. if (nodes.size() == 1) {
  50. cout << 0 << endl;
  51. return 0;
  52. }
  53.  
  54. // each edge needs to be traversed twice (down and back up)
  55. int result = 2 * (nodes.size() - 1);
  56. cout << result << endl;
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
6