-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.cpp
executable file
·52 lines (38 loc) · 1.21 KB
/
solution.cpp
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
#include <bits/stdc++.h>
using namespace std;
int dfs(vector<vector<int>>& adjList, vector<int>& kavrazLevels, int node, int parent) {
// leaves
if (adjList[node].size() == 1 && adjList[node][0] == parent) {
return kavrazLevels[node] = 0;
}
// for internal nodes, find the kavraz levels of all nodes in subtree
vector<int> childKavrazLevels;
for (int next_node : adjList[node]) {
if (next_node != parent)
childKavrazLevels.push_back(dfs(adjList, kavrazLevels, next_node, node));
}
sort(childKavrazLevels.begin(), childKavrazLevels.end(), greater<int>());
int maxDepth = 0;
for (int i = 0; i < childKavrazLevels.size(); i++) {
maxDepth = max(maxDepth, childKavrazLevels[i] + i + 1);
}
return kavrazLevels[node] = maxDepth;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<vector<int>> adjList(n);
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
adjList[x].push_back(y);
adjList[y].push_back(x);
}
int root;
cin >> root;
vector<int> kavrazLevels(n + 1);
cout << dfs(adjList, kavrazLevels, root, -1);
return 0;
}