일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 플로이드 와샬
- NEXT
- 백트래킹
- 문자열
- 이분 탐색
- 가끔은_말로
- pytorch
- DP
- 자바스크립트
- c++
- lazy propagation
- 조합론
- dfs
- tensorflow
- 회고록
- 세그먼트 트리
- 2023
- 가끔은 말로
- dropout
- 다익스트라
- 분할 정복
- 미래는_현재와_과거로
- 우선 순위 큐
- BFS
- 너비 우선 탐색
- 알고리즘
- 크루스칼
- Overfitting
- object detection
- back propagation
Archives
- Today
- Total
Doby's Lab
백준 1761번: 정점들의 거리 (C++) 본문
https://www.acmicpc.net/problem/1761
1761번: 정점들의 거리
첫째 줄에 노드의 개수 N이 입력되고 다음 N-1개의 줄에 트리 상에 연결된 두 점과 거리를 입력받는다. 그 다음 줄에 M이 주어지고, 다음 M개의 줄에 거리를 알고 싶은 노드 쌍이 한 줄에 한 쌍씩
www.acmicpc.net
Solved By: LCA
Sparse Table을 이용해 LCA만 구할 수 있었지만, 각 정점들 간의 거리 또한 Sparse Table로 parent node들을 구하듯이 거리를 구할 수 있습니다.
parent를 구하는 점화식과 유사합니다. Sparse Table을 아는 상태에서 조금 더 생각해보면 충분히 나올 수 있는 점화식입니다.
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#define MAX 40001
#define LOG_MAX 16
#define pii pair<int, int>
using namespace std;
int n, k;
int parent[MAX][LOG_MAX];
int dist[MAX][LOG_MAX];
int level[MAX];
vector<pii> adj[MAX];
void dfs(int now, int par){
for(int i = 0; i < adj[now].size(); i++){
int next = adj[now][i].first;
int cost = adj[now][i].second;
if(next == par) continue;
parent[next][0] = now;
level[next] = level[now] + 1;
dist[next][0] = cost;
dfs(next, now);
}
}
void swap(int *a, int *b){
int* temp = a;
a = b;
b = temp;
}
int lca(int a, int b){
int res = 0;
int maxV = 0, minV = 1e9;
if(level[a] < level[b]) swap(a, b);
int diff = level[a] - level[b];
for(int i = LOG_MAX - 1; i >= 0; i--){
if(diff >= 1 << i){
diff -= 1 << i;
res += dist[a][i];
a = parent[a][i];
}
}
if(a != b){
for(int i = LOG_MAX - 1; i >= 0; i--){
if(parent[a][i] != 0 && parent[a][i] != parent[b][i]){
res += (dist[a][i] + dist[b][i]);
a = parent[a][i];
b = parent[b][i];
}
}
res += dist[a][0];
res += dist[b][0];
}
return res;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for(int i = 0; i < n - 1; i++){
int a, b, c; cin >> a >> b >> c;
adj[a].push_back({b, c});
adj[b].push_back({a, c});
}
dfs(1, 0);
for(int j = 1; j < LOG_MAX; j++){
for(int i = 1; i <= n; i++){
parent[i][j] = parent[parent[i][j - 1]][j - 1];
dist[i][j] = dist[parent[i][j - 1]][j - 1] + dist[i][j - 1];
}
}
cin >> k;
while(k--){
int a, b; cin >> a >> b;
cout << lca(a, b) << '\n';
}
return 0;
}
728x90
'PS > BOJ' 카테고리의 다른 글
백준 7742번: Railway (C++) (0) | 2022.05.03 |
---|---|
백준 3176번: 도로 네트워크 (C++) (0) | 2022.05.03 |
백준 14425번: 문자열 집합 (C++) (0) | 2022.05.02 |
백준 1302번: 베스트셀러 (C++) (0) | 2022.05.02 |
백준 15783번: 세진 바이러스 (C++) (0) | 2022.05.01 |