int StonesOnATree::minStones(vector <int> p, vector <int> w); |
p = { 0, 1, 2, 3 }
w = { 1, 2, 2, 4, 4 }
The tree is a line 0 - 1 - 2 - 3 - 4. You play the game optimally as follows:
If you play the game in this manner, your optimal score will be 8.
p = { 0, 0 }
w = { 1, 2, 3 }
Answer: 6
p = { 0 }
w = { 100000, 100000 }
Answer: 200000
p = {0, 0, 1, 1, 2, 2}
w = {1, 1, 1, 1, 1, 1, 1}
Answer: 4
p = {0, 0, 1, 2, 3, 4, 4, 2, 1, 3, 6, 7}
w = {1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8, 9, 10}
Answer: 22
What I did was convert p to an adjacency list representation. I have a vector of vectors of integers called Adj, where Adj[i] is a vector of the id's of the children of node i. And I stored w in the class in a vector named W.
You should stop here and add Adj and W to the StonesOnATree class, and create them from p and w. Print them out and verify that they are correct for the examples.
Next, I wrote added a method called S() to the class:
int StonesOnATree::S(int n); |
This solves the problem for the subtree rooted at node n. S(n) performs a postorder traversal, so when you call it on a node n, you'll do the following:
I'm not telling you how to do this calculation -- I want you to use your logic skills to figure it out.
Here is ASCII art for the last example, which should help you a lot!
---------------------
| N: 0 |
| W[0]: 1 |
| Adj[0] = { 1, 2 } |
| S(0) = 22 |
---------------------
/ \
/-----/ \-----\
/ \
--------------------- ---------------------
| N: 1 | | N: 2 |
| W[1] = 2 | | W[2] = 3 |
| Adj[1] = { 3, 9 } | | Adj[2] = { 4, 8 } |
| S(1) = 18 | | S(2) = 22 |
--------------------- ---------------------
/ \ / \
--------------------- --------------------- --------------------- ---------------------
| N: 3 | | N: 9 | | N: 4 | | N: 8 |
| W[3] = 4 | | W[9] = 8 | | W[4] = 5 | | W[8] = 8 |
| Adj[3] = { 5, 10 }| | Adj[9] = {} | | Adj[4] = { 6, 7 } | | Adj[8] = {} |
| S(3) = 18 | | S(9) = 8 | | S(4) = 22 | | S(8) = 8 |
--------------------- --------------------- --------------------- ---------------------
/ \ / \
--------------------- --------------------- --------------------- ---------------------
| N: 5 | | N: 10 | | N: 6 | | N: 7 |
| W[5] = 6 | | W[10] = 8 | | W[6] = 6 | | W[7] = 7 |
| Adj[5] = {} | | Adj[10] = {} | | Adj[6] = { 11 } | | Adj[7] = { 12 } |
| S(5) = 6 | | S(10) = 8 | | S(6) = 15 | | S(7) = 17 |
--------------------- --------------------- --------------------- ---------------------
| |
--------------------- ---------------------
| N: 11 | | N: 12 |
| W[11] = 9 | | W[12] = 10 |
| Adj[11] = {} | | Adj[12] = {} |
| S(11) = 9 | | S(12) = 10 |
--------------------- ---------------------