You have a tree (N nodes, undirected). each node can be colored as black or white. 2 node can be connected if they are both white and the path between 2 nodes is the set of only black nodes or these 2 nodes can move to each other by 1 edge.

the problem is you need to color the tree to have the maximum connected pair of nodes

test

inp: first line contains T(T<=10) is the number of test cases, next is N (N<=5000) is the number of nodes in the tree,

N-1 next lines is an edge connected 2 nodes U and V

output: each test case output 1 number is the maximum pair of nodes can be connected

inp:

2

8

1 2

2 3

2 4

4 5

5 6

6 7

6 8

2

1 2

out:

7

1

Call dp[i][j]: The answer for the subtree of i, j represents how many new pairs will be created if i is painted white.

The recurrence is simple:

- Paint vertex i white, for each child v get the maximum of dp[v][j] + j. Set dp[i][1] to the sum of these on all children.
- Paint vertex i black. dp[i][j] = dp[i][j - k] + dp[v][k] + k * (j - k) (j - k white nodes in i’s subtree is connected to k white nodes in v’s subtree).

The total complexity is O(T * N ^ 2), which is enough to pass the task.

Please post the link of problem

thank you so much