Doby's Lab

백준 7742번: Railway (C++) 본문

PS/BOJ

백준 7742번: Railway (C++)

도비(Doby) 2022. 5. 3. 22:13

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