๋ฌธ์
์ฝ๋
#include <iostream>
#include <vector>
#define MAX 40001
using namespace std;
int N, M, max_height;
int depth[MAX];
vector<pair<int,int>>graph[MAX];
bool visited[MAX];
int parent[MAX][30];
int dist[MAX][30];
void dfs(int node, int _depth){
visited[node] = 1;
depth[node] = _depth;
for(auto next: graph[node]){
if(visited[next.first]) continue;
parent[next.first][0] = node;
dist[next.first][0] = next.second;
dfs(next.first, _depth+1);
}
}
void set_parent(){
for(int i = 1; i<max_height; i++){
for(int k=1; k<=N; k++){
int prev_parent = parent[k][i-1];
parent[k][i] = parent[prev_parent][i-1];
if(parent[prev_parent][i-1] == 0) continue;
dist[k][i] = dist[k][i-1] + dist[prev_parent][i-1];
}
}
}
int lca(int a, int b){
int _dist = 0;
if(depth[a] > depth[b]) swap(a, b);
for(int i=max_height; i>=0; i--){ // ๊น์ด ๋ง์ถ๊ธฐ
int diff = depth[b] - depth[a];
int jump = 1 << i;
if(jump <= diff){
_dist += dist[b][i];
b = parent[b][i];
}
}
if(a == b) return _dist;
for(int i=max_height; i>=0; i--){ // ์กฐ์์ ํฅํด ์ฌ๋ผ๊ฐ๊ธฐ
if(parent[a][i] != parent[b][i]){
_dist += dist[a][i];
a = parent[a][i];
_dist += dist[b][i];
b = parent[b][i];
}
}
_dist += dist[a][0] + dist[b][0]; //2์นธ์ฉ ์ฌ๋ผ๊ฐ์์ผ๋, ๋ฐ๋ก ํ์นธ ์์ ๊ฑฐ๋ฆฌ๋ฅผ ๋ํด์ค๋ค.
return _dist;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin>>N;
int temp = N;
while(temp>0){
max_height++;
temp = temp >> 1;
}
for(int i=0; i<N-1; i++){
int a, b, c; cin>>a>>b>>c;
graph[a].push_back({b,c}); // a ์์ b๋ก ๊ฐ๋๋ฐ c๊น์ง์ ๊ฑฐ๋ฆฌ
graph[b].push_back({a,c}); // ์ ๋ฐฉํฅ ์ฐ๊ฒฐ
}
dfs(1, 0);
set_parent();
cin>>M;
for(int i=0; i<M; i++){
int a, b; cin>>a>>b;
cout<<lca(a, b)<<'\n';
}
}
ํ์ด
์์ ๊ฐ์ ๋ LCA๋ฅผ ํ์ฉํ์ฌ ํธ๋ ๋ฌธ์ ์ ๋๋ค.
- ๊ฐ ๋ ธ๋์ ๋์ด๋ฅผ ๊ธฐ๋กํ ๋ ๊ฐ ๋ ธ๋์ ๋ฐ๋ก ์ ๋ ธ๋๊น์ง์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ธฐ๋กํฉ๋๋ค.
- ๊ฐ ๋ ธ๋์ ๋์ด๋ฅผ ๋ง์ถฐ์ค๋ ๋์ด๋ฅผ ๋ง์ถ ๋ ธ๋์ ๊ฑฐ๋ฆฌ๋ฅผ ๋ํฉ๋๋ค.
- LCA ์๊ณ ๋ฆฌ์ฆ์ ํตํด์ ์กฐ์์ ์ฐพ์์ ์ฌ๋ผ๊ฐ ๋ ๊ฑฐ๋ฆฌ๋ฅผ ๋ํฉ๋๋ค.
- LCA ์๊ณ ๋ฆฌ์ฆ์ ํตํด์ 2์ ์ ๊ณฑํํ๋ก ์ฌ๋ผ๊ฐ์ผ๋ ์ด๊ธฐ ์์ ๋ ธ๋์ ํ ์นธ ์ ๋ ธ๋๊น์ง์ ๊ฑฐ๋ฆฌ๋ฅผ ๋ํด์ค๋๋ค.
'Algorithm ๐ง๐ปโ๐ป > ๋ฐฑ์ค(BOJ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค,c++] 4195๋ฒ - ์น๊ตฌ ๋คํธ์ํฌ (0) | 2022.09.02 |
---|---|
[๋ฐฑ์ค,c++] 18116๋ฒ - ๋ก๋ด ์กฐ๋ฆฝ (0) | 2022.09.02 |
[๋ฐฑ์ค,c++] 17144๋ฒ - ๋ฏธ์ธ๋จผ์ง ์๋ ! (0) | 2022.09.02 |
[๋ฐฑ์ค,c++] 11438๋ฒ - LCA 2 (0) | 2022.08.30 |
[๋ฐฑ์ค,c++] 16236๋ฒ - ์๊ธฐ ์์ด (0) | 2022.08.28 |
[๋ฐฑ์ค,c++] 15686๋ฒ - ์นํจ ๋ฐฐ๋ฌ (0) | 2022.08.26 |
๋๊ธ