メモジャンボ

良い感じのブログタイトル募集中

隣接リスト 幅優先探索(ABC 070 D問題)

隣接行列よりちょっと難しくないですか?
問題
以下ネタバレ注意
  1. using edge = struct { int to; ll cost; };
  2. vector<edge>tree[100010];
  3. ll depth[100010];
  4. int x[100010], y[100010];
  5. int N, Q, K;
  6.  
  7. void bfs(int K) {
  8. queue<int> que;
  9. REP(i, N) {
  10. depth[i] = INF;
  11. }
  12. que.push(K);
  13. depth[K] = 0;
  14. while (que.size()) {
  15. int p = que.front(); que.pop();
  16. for (auto &e : tree[p]) {
  17. if (depth[e.to] == INF) {
  18. que.push(e.to); depth[e.to] = depth[p] + e.cost;
  19. }
  20. }
  21. }
  22. }
  23.  
  24. int main() {
  25. cin >> N;
  26. REP(i, N - 1) {
  27. int a, b, c;
  28. cin >> a >> b >> c;
  29. a--, b--;
  30. tree[a].push_back({ b,c });
  31. tree[b].push_back({ a,c });
  32. }
  33. cin >> Q >> K;
  34. K--;
  35. bfs(K);
  36. REP(i, Q) {
  37. cin >> x[i] >> y[i];
  38. x[i]--; y[i]--;
  39. }
  40.  
  41. REP(i, Q) {
  42. cout << depth[x[i]] + depth[y[i]] << endl;
  43. }
  44. return 0;
  45. }