BOJ3176: 도로 네트워크

https://www.acmicpc.net/problem/3176

  • LCA를 따라서 계산하는 확장판. 대충 LCA 활용 문제의 표본 같은 문제인듯.
  • 두 점사이의 경로 와 관련된 모든 문제들을 풀 수 있을듯.
  • 아이디어도 잘 떠올렸고, 코드 작성도 만족스러웠음. 113줄을 짜면서 컴파일 에러가 안남!
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <bits/stdc++.h>
using namespace std;

struct Edge {
  int v, c;
};

const int E = 18;
const int INF = 1000000001;
class Tree {
  int N;
  vector<vector<Edge>> adj;
  vector<int> depth;
  vector<vector<int>> parent, minD, maxD;
public:
  Tree(int n);
  void input();
  void dfs(int u, int p, int d);
  void fillTable();
  void answerQuery();
  void lcaDist(int a, int b);
};

Tree::Tree(int n): N(n), adj(n+1), depth(n+1) {
  parent.resize(n+1, vector<int>(E));
  minD.resize(n+1, vector<int>(E, INF));
  maxD.resize(n+1, vector<int>(E));
}

void Tree::input() {
  for(int i = 0; i < N-1; i++) {
    int u, v, c;
    scanf("%d%d%d", &u, &v, &c);
    adj[u].push_back({v,c});
    adj[v].push_back({u,c});
  }
}

void Tree::dfs(int u, int p, int d) {
  depth[u] = d;
  for(auto [v, c]: adj[u]) {
    if (v == p) continue;
    parent[v][0] = u;
    minD[v][0] = c;
    maxD[v][0] = c;
    dfs(v, u, d+1);
  }
}

void Tree::fillTable() {
  for(int i = 1; i < E; i++) {
    for(int j = 1; j <= N; j++) {
      int P = parent[j][i-1];
      parent[j][i] = parent[P][i-1];
      minD[j][i] = min(minD[j][i-1], minD[P][i-1]);
      maxD[j][i] = max(maxD[j][i-1], maxD[P][i-1]);
    }
  }
}

void Tree::lcaDist(int a, int b) {
  if(depth[a] > depth[b]) swap(a,b);
  int maxDist = 0, minDist = INF;

  for(int i = E-1; i >= 0; i--) {
    if(depth[b] - depth[a] >= (1 << i)) {
      minDist = min(minDist, minD[b][i]);
      maxDist = max(maxDist, maxD[b][i]);
      b = parent[b][i];
    }
  }
  
  if(a == b) {
    printf("%d %d\n", minDist, maxDist);
    return;
  }

  for(int i = E-1; i >= 0; i--) {
    if(parent[a][i] != parent[b][i]) {
      minDist = min(minDist, minD[b][i]);
      maxDist = max(maxDist, maxD[b][i]);
      minDist = min(minDist, minD[a][i]);
      maxDist = max(maxDist, maxD[a][i]);
      a = parent[a][i];
      b = parent[b][i];
    }
  }
  minDist = min(minDist, minD[b][0]);
  maxDist = max(maxDist, maxD[b][0]);
  minDist = min(minDist, minD[a][0]);
  maxDist = max(maxDist, maxD[a][0]);
  printf("%d %d\n", minDist, maxDist);
}

void Tree::answerQuery() {
  int K, a, b;
  scanf("%d", &K);
  for(int i = 0; i < K; i++) {
    scanf("%d%d", &a, &b);
    lcaDist(a,b);
  }
}

int main() {
  int N;
  scanf("%d", &N);
  Tree tree(N);
  tree.input();
  tree.dfs(1, -1, 0);
  tree.fillTable();
  tree.answerQuery();
}