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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 166 |
2 | maomao90 | 163 |
2 | Um_nik | 163 |
4 | atcoder_official | 161 |
5 | adamant | 160 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
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