隣接リスト 幅優先探索(ABC 070 D問題)
隣接行列よりちょっと難しくないですか?
問題
以下ネタバレ注意
問題
以下ネタバレ注意
- using edge = struct { int to; ll cost; };
- vector<edge>tree[100010];
- ll depth[100010];
- int x[100010], y[100010];
- int N, Q, K;
- void bfs(int K) {
- queue<int> que;
- REP(i, N) {
- depth[i] = INF;
- }
- que.push(K);
- depth[K] = 0;
- while (que.size()) {
- int p = que.front(); que.pop();
- for (auto &e : tree[p]) {
- if (depth[e.to] == INF) {
- que.push(e.to); depth[e.to] = depth[p] + e.cost;
- }
- }
- }
- }
- int main() {
- cin >> N;
- REP(i, N - 1) {
- int a, b, c;
- cin >> a >> b >> c;
- a--, b--;
- tree[a].push_back({ b,c });
- tree[b].push_back({ a,c });
- }
- cin >> Q >> K;
- K--;
- bfs(K);
- REP(i, Q) {
- cin >> x[i] >> y[i];
- x[i]--; y[i]--;
- }
- REP(i, Q) {
- cout << depth[x[i]] + depth[y[i]] << endl;
- }
- return 0;
- }