일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 자바스크립트
- 다익스트라
- DP
- lazy propagation
- 문자열
- 우선 순위 큐
- NEXT
- object detection
- 너비 우선 탐색
- 회고록
- 분할 정복
- 알고리즘
- 가끔은 말로
- 플로이드 와샬
- c++
- 미래는_현재와_과거로
- dropout
- dfs
- 크루스칼
- 세그먼트 트리
- 2023
- 가끔은_말로
- BFS
- tensorflow
- 백트래킹
- 조합론
- 이분 탐색
- pytorch
- Overfitting
- back propagation
Archives
- Today
- Total
Doby's Lab
백준 7742번: Railway (C++) 본문
https://www.acmicpc.net/problem/7742
7742번: Railway
The first line of the input contains the integers N and Q (in this order) separated by a single space. N is the number of cities, 1 ≤ N ≤ 100 000, and Q is the number of queries, 1 ≤ Q ≤ 2 000 000 000. For simplicity, the cities are numbered by the
www.acmicpc.net
Solved By: LCA
1761과 같은 문제입니다. (https://draw-code-boy.tistory.com/305)
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#define MAX 100001
#define LOG_MAX 17
#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 >> k;
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];
}
}
while(k--){
int a, b; cin >> a >> b;
cout << lca(a, b) << '\n';
}
return 0;
}
'PS > BOJ' 카테고리의 다른 글
백준 13059번: Tourists (C++) (0) | 2022.05.05 |
---|---|
백준 9742번: 순열 (C++) (0) | 2022.05.04 |
백준 3176번: 도로 네트워크 (C++) (0) | 2022.05.03 |
백준 1761번: 정점들의 거리 (C++) (0) | 2022.05.03 |
백준 14425번: 문자열 집합 (C++) (0) | 2022.05.02 |