[Link] https://www.acmicpc.net/problem/2250
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
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
// #include <bits/stdc++.h>
using namespace std;
#define for0(i, n) for(int i = 0; i < n; i++)
#define for1(i, n) for(int i = 1; i < n; i++)
#define fori(s, e) for(int i = s; i < e; i++)
#define endl "\n"
typedef long long ll;
const int INF = 987654321;
const int MAX = 100;
int n, mmax = 1, space_from_left = 0, max_depth;
int depth = 0, width = 0;
class Node {
public:
int idx;
int depth = 0;
int space_from_left = 0;
Node* left;
Node* right;
Node(int _idx): idx(_idx), left(NULL), right(NULL) {}
Node() {}
};
vector<Node> nodes;
vector<pair<int, int>> min_max;
void set_depth_dfs(Node *node, int depth) {
node->depth = depth;
max_depth = max(max_depth, depth);
if(node -> left != NULL) set_depth_dfs(node->left, depth + 1);
node -> space_from_left = space_from_left++;
min_max[depth].first = min(min_max[depth].first, space_from_left);
min_max[depth].second = max(min_max[depth].second, space_from_left);
if(node -> right != NULL) set_depth_dfs(node->right, depth+1);
}
void get_max_bfs(Node *node) {
for0(i, max_depth + 1) {
if(width == abs(min_max[i].first - min_max[i].second)) {
depth = min(depth, i);
} else if(width < abs(min_max[i].first - min_max[i].second)) {
depth = i;
width = abs(min_max[i].first - min_max[i].second);
}
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
for0(i, n) {
nodes.push_back(Node(i));
min_max.push_back(make_pair(INF, -INF));
}
vector<bool> is_root(n, true);
for0(i, n) {
int node, a, b; cin >> node >> a >> b;
if(a != -1) {
nodes[node - 1].left = &nodes[a - 1];
is_root[a - 1] = false;
}
if(b != -1) {
nodes[node - 1].right = &nodes[b - 1];
is_root[b - 1] = false;
}
}
int root = 0;
for0(i, n) if(is_root[i]) root = i;
set_depth_dfs(&nodes[root], 0);
get_max_bfs(&nodes[root]);
cout << depth + 1 << " " << width + 1;
return 0;
}