Title Description
Recall the KMP algorithm and Trie diagram for Hiho 03 and Hiho 04.
The Trie figure is actually doing KMP on the tree.
In the same way, the motion in the tree is actually ... Make a move on the tree.
The previous motion is done on a linear table, there is only one path, there are multiple paths on the tree, but there is no difference in nature.
State F[i, j] means that the tree containing the root node in the root is the largest and the maximum of the connected components of a J node.
State transition equation: F[i, j] = Max (F[i, J], F[i, j–k] + f[i_child, K]), where i_child represents the child node of I.
It should be noted that the transfer sequence, J should be from large to small transfer: when I_child determined, calculate f[i, j] need to use F[i, J–k], at this time f[i, j–k] should not use i_child this subtrees tree node.
The status of the result is expressed as f[1, M].
#include <iostream> #include <algorithm> #include <vector>using namespace std;vector<int> tree [105];int f[105][105];int N, m;void dfs (int root_idx, int pa_idx) {int len = tree[root_idx].size (); for (int i = 0; i < Len i++) {int sub_idx = tree[root_idx][i];if (sub_idx! = pa_idx) {dfs (SUB_IDX, root_idx); (int j = m; j > 1; j--) {for ( int k = 1; K < J; k++) {F[root_idx][j] = max (F[root_idx][j], f[root_idx][j-k] + f[sub_idx][k]);}}}} int main () {cin >> n >> m;for (int i = 1; I <= n; i++) {cin >> f[i][1];} for (int i = 1; i < n; i++) {int A, b;cin >> a >> b;tree[a].push_back (b); Tree[b].push_back (a);} DFS (1, 0); cout << f[1][m] << endl;return 0;}
[Hiho 12] The motion of the tree