Блог пользователя negativez2

Автор negativez2, история, 7 лет назад, По-английски

Statement:

Given a tree of N nodes, every node i have a value A[i].

You have to find the maximum value you can get by picking a subtree (a subgraph of the tree which is also a tree) of exactly K nodes.

Constrain : 1 <= K,N <= 1000

This can be solve in O(n^3) by a simple dp, but after spending time thinking, I couldnt find a better solution. Can anyone solve this in O(n^2) ?

Help is appreciated.

  • Проголосовать: нравится
  • +17
  • Проголосовать: не нравится

»
7 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Perhaps I don't understand something about this problem, but why can't you just do two rounds of DFS?

1st round cumulates the size of each node's subtree. 2nd round cumulates the total value of a subtree.

Then do an O(n) for loop passing through each node, checking if its first round result = K, and then taking the maximum of those second round results.

I don't think DP is needed. Are you sure you understood the problem correctly? ;}