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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
|
#include <iostream>
#include <vector>
#include <queue>
#define INF 987654321
#define MAXX 100001
using namespace std;
int p[21][MAXX], min_len[21][MAXX], max_len[21][MAXX];
int depth[MAXX];
bool visited[MAXX];
typedef long long ll;
typedef pair<int, int> pp;
vector<pp> edges[MAXX];
void bfs()
{
queue<int> q;
q.push(1);
visited[1] = 1;
depth[1] = 1;
while (!q.empty())
{
int now = q.front();
q.pop();
for (auto i : edges[now])
{
//now에 연결된 간선
if (!visited[i.first])
{
visited[i.first] = true;
depth[i.first] = depth[now] + 1;
min_len[0][i.first] = min(min_len[0][i.first], i.second);
max_len[0][i.first] = max(min_len[0][i.first],i.second);
p[0][i.first] = now;
q.push(i.first);
}
}
}
}
void setParent(int n)
{
for (int i = 1; i < 21; i++)
{
for (int j = 1; j <= n; j++)
{
p[i][j] = p[i - 1][p[i - 1][j]];
min_len[i][j] = min(min_len[i-1][j], min_len[i - 1][p[i - 1][j]]);
max_len[i][j] = max(max_len[i-1][j], max_len[i - 1][p[i - 1][j]]);
}
}
}
void lca(int a, int b)
{
int maxL = -1, minL = 987654321;
if (depth[a] > depth[b])
{
int tmp = a;
a = b;
b = tmp;
}
int i = 20;
while (i >= 0)
{
if ((depth[b] - depth[a]) >= (1 << i))
{
maxL = max(maxL, max_len[i][b]);
minL = min(minL, min_len[i][b]);
b = p[i][b];
}
i--;
}
if (b != a)
{
i = 20;
while (i >= 0)
{
if (p[i][a] != p[i][b])
{
maxL = max(maxL, max(max_len[i][a], max_len[i][b]));
minL = min(minL, min(min_len[i][a], min_len[i][b]));
a = p[i][a];
b = p[i][b];
}
i--;
}
maxL = max(maxL, max(max_len[0][a], max_len[0][b]));
minL = min(minL, min(min_len[0][a], min_len[0][b]));
}
cout << minL << " " << maxL << '\n';
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n;
for (int i = 0; i < 21; i++)
{
for (int j = 1; j <= n; j++)
{
min_len[i][j] = 987654321;
max_len[i][j] = -1;
}
}
for (int i = 0; i < n - 1; i++)
{
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(pp(b, c));
edges[b].push_back(pp(a, c));
}
bfs();
setParent(n);
cin >> k;
while (k--)
{
int a, b;
cin >> a >> b;
lca(a, b);
}
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
'BOJ > C++' 카테고리의 다른 글
최단경로 (0) | 2020.02.11 |
---|---|
단절점 (0) | 2020.02.11 |
[BOJ] 두 배열의 합 (0) | 2020.02.10 |
[BOJ] 합이 0인 네 정수 (0) | 2020.02.10 |
교수님은 기다리지 않는다 (0) | 2020.02.10 |