We are given an array A of size n ( n <= 1000) , where A[i] = number of nodes in the level i of the tree.
Given this information, what is the maximum possible diameter of the tree. Can anyone help?
# | User | Rating |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
We are given an array A of size n ( n <= 1000) , where A[i] = number of nodes in the level i of the tree.
Given this information, what is the maximum possible diameter of the tree. Can anyone help?
Name |
---|
For a brute force solution, try to construct a tree. Then select a random node $$$p$$$. Do the first bfs/dijkstra to get the furthest vertice $$$u$$$ from $$$p$$$. Do the second bfs/dijkstra to get the furthest vertice $$$v$$$ from $$$p$$$. Then $$$u-v$$$ is the furthest pair in tree, hence the diameter of the tree is the distance from $$$u$$$ to $$$v$$$
For your problem, we move from the root of some subtrees to the furthest possible node $$$u$$$ in the left, remove it from the tree and do the same thing with furthest possible node $$$v$$$ in the right. The diameter of the tree is the distance from $$$u$$$ to $$$v$$$
Any solution other than brute force?
The approaching of not attempting to construct such trees are choosing some substree's root and try to lowest leaf $$$u$$$ and erase the path, then do again and get vertice $$$v$$$, then $$$u-v$$$ would be the diameter of that subtree. The maximal over all diameters is diameter of the whole tree (Removing the path from $$$x$$$ to $$$y$$$ means to reduce the number of nodes of $$$a[x], a[x + 1], ..., a[y - 1], a[y]$$$, all by one)
The number of ways of choosing such subtree is $$$O(n)$$$ and finding diameter in $$$O(n)$$$. But there is still a way to improve this from $$$O(n^2)$$$ solution to linear $$$O(n)$$$ that is to using DP