Given a binary tree with n leaves and a set of C colors. Each leaf node of the tree is given a unique color from the set C. Thus no leaf nodes have the same color. The internal nodes of the tree are uncolored. Every pair of colors in the set C has a cost associated with it. So if a tree edge connects two nodes of colors A and B, the edge cost is the cost of the pair (A, B). Our aim is to give colors to the internal nodes of the tree, minimizing the total edge cost of the tree.
I have working on this problem for hours now, and haven’t really come up with a working solution. Any hints would be appreciated.
I am going to solve the problem with pseudocode, because I tried writing explanation and it was completely not understandable even for me. Hopefully the code will do the trick. The complexity of my solution is not very good – memory an druntime in O(C^2 * N).
I will need couple of arrays I will be using in dynamic approach to your task:
dp [N][C][C]->dp[i][j][k]the maximum price you can get from a tree rooted at nodei, if you paint it in colorjand its parent is colored in colorkmaxPrice[N][C]->maxPrice[i][j]the maximum price you can get from a tree rooted in nodeiif its parent is colored in colorjcolor[leaf]-> the color of the leafleafprice[C][C]->price[i][j]the price you get if you have pair of neighbouring nodes with colorsiandjchosenColor[N][C]->chosenColor[i][j]the color one should choose for nodeito obtainmaxPrice[i][j]Lets assume the nodes are ordered using topological sorting, i.e we will be processing first leaves. Topological sorting is very easy to do in a tree. Let the sorting have given a list of inner nodes
inner_nodes