LCA 문제다.
a,b 의 LCA를 찾는 동안 누적된 거리를 출력하면 된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #include <stdio.h> #include <vector> #include <queue> using namespace std; typedef pair<int, int> pii; int d[50001], n, u, v, m, w; pii p[50001]; vector<pii> adj[50001]; void bfs(int nod) { queue<int> q; d[nod] = 1; q.push(nod); while (q.size()) { int x = q.front(); q.pop(); for (auto i : adj[x]) { if (d[i.first]) continue; q.push(i.first); d[i.first] = d[x] + 1; p[i.first].first = x; p[i.first].second = i.second; } } } int main() { scanf("%d", &n); n--; while (n--) { scanf("%d%d%d", &u, &v, &w); adj[u].push_back({ v, w }); adj[v].push_back({ u, w }); } int i; for (i = 0; !adj[i].size(); i++); bfs(i); scanf("%d", &m); int ans; while (m--) { ans = 0; scanf("%d%d", &u, &v); while (d[u] < d[v]) { ans += p[v].second; v = p[v].first; } while (d[v] < d[u]) { ans += p[u].second; u = p[u].first; } while (u != v) { ans += p[v].second + p[u].second; v = p[v].first; u = p[u].first; } printf("%d\n", ans); } return 0; } | cs |
'BOJ' 카테고리의 다른 글
4963 섬의 개수 (0) | 2018.02.18 |
---|---|
11812 K진 트리 (0) | 2018.02.18 |
11437 LCA (0) | 2018.02.17 |
3111 검열 (0) | 2018.02.17 |
2841 외계인의 기타 연주 (0) | 2018.02.17 |