There's an existing question dealing with trees where the weight of a vertex is its degree, but I'm interested in the case where the vertices can have arbitrary weights.
This isn't homework but it is one of the questions in the algorithm design manual, which I'm currently reading; an answer set gives the solution as
- Perform a DFS, at each step update Score[v][include], where v is a vertex and include is either true or false;
- If v is a leaf, set Score[v][false] = 0, Score[v][true] = wv, where wv is the weight of vertex v.
- During DFS, when moving up from the last child of the node v, update Score[v][include]: Score[v][false] = Sum for c in children(v) of Score[c][true] and Score[v][true] = wv + Sum for c in children(v) of min(Score[c][true]; Score[c][false])
- Extract actual cover by backtracking Score.
However, I can't actually translate that into something that works. (In response to the comment: what I've tried so far is drawing some smallish graphs with weights and running through the algorithm on paper, up until step four, where the "extract actual cover" part is not transparent.)
In response Ali's answer: So suppose I have this graph, with the vertices given by A
etc. and the weights in parens after:
A(9)---B(3)---C(2)
\ \
E(1) D(4)
The right answer is clearly {B,E}
.
Going through this algorithm, we'd set values like so:
score[D][false] = 0
;score[D][true] = 4
score[C][false] = 0
;score[C][true] = 2
score[B][false] = 6
;score[B][true] = 3
score[E][false] = 0
;score[E][true] = 1
score[A][false] = 4
;score[A][true] = 12
Ok, so, my question is basically, now what? Doing the simple thing and iterating through the score
vector and deciding what's cheapest locally doesn't work; you only end up including B
. Deciding based on the parent and alternating also doesn't work: consider the case where the weight of E
is 1000
; now the correct answer is {A,B}
, and they're adjacent. Perhaps it is not supposed to be confusing, but frankly, I'm confused.