(rephrasing one of the editorial solutions)
Suppose we are growing the tree as follows. On each step, there are 3 groups of nodes: Black, Gray, and White. The Black nodes are those whose degrees are known. Each Gray node is connected to exactly one of the Black nodes. Each White node is not connected to anything yet. On each step, we grow the tree by selecting a set S of 0 or more White nodes and connecting them all to one of the Gray nodes which we will call X. We mark X as Black and S as Gray.
The solution is to write a recurrent relation f(numberOfGray, numberOfWhite). Note that one of the nodes in the optimal tree will have degree one. Suppose we select that node as the root. Then the answer to the whole problem is score[0] + f(1, n-2). That is, we start with 1 Black, 1 Gray, and N-2 White nodes. The Black node has degree 1, thus we add score[0] to our answer. f(1,n-2) will account for the degrees of the Gray and White nodes as they turn Black. The recurrent relation is f(nGray, nWhite) = max_k score[k]+f(nGray-1+k, nWhite-k).
Code:
int solve(vector sco) {
int n = sco.size()+1;
int f[55][55];
for (int sum = 1; sum <= n-1; sum++) {
for (int u = 0; u <= sum; u++) {
int r = sum - u;
int& ret = f[u][r] = -1;
if (u==0) {
ret = (r==0 ? 0 : -1);
continue;
}
if (r==0) {
ret = sco[0]*u;
continue;
}
for (int x = 0; x <= r; x++) {
int z = f[u-1+x][r-x];
if (z >= 0)
ret = max(ret, z + sco[x]);
}
}
}
return f[1][n-2]+sco[0];
}
Suppose we are growing the tree as follows. On each step, there are 3 groups of nodes: Black, Gray, and White. The Black nodes are those whose degrees are known. Each Gray node is connected to exactly one of the Black nodes. Each White node is not connected to anything yet. On each step, we grow the tree by selecting a set S of 0 or more White nodes and connecting them all to one of the Gray nodes which we will call X. We mark X as Black and S as Gray.
The solution is to write a recurrent relation f(numberOfGray, numberOfWhite). Note that one of the nodes in the optimal tree will have degree one. Suppose we select that node as the root. Then the answer to the whole problem is score[0] + f(1, n-2). That is, we start with 1 Black, 1 Gray, and N-2 White nodes. The Black node has degree 1, thus we add score[0] to our answer. f(1,n-2) will account for the degrees of the Gray and White nodes as they turn Black. The recurrent relation is f(nGray, nWhite) = max_k score[k]+f(nGray-1+k, nWhite-k).
Code:
int solve(vector
int n = sco.size()+1;
int f[55][55];
for (int sum = 1; sum <= n-1; sum++) {
for (int u = 0; u <= sum; u++) {
int r = sum - u;
int& ret = f[u][r] = -1;
if (u==0) {
ret = (r==0 ? 0 : -1);
continue;
}
if (r==0) {
ret = sco[0]*u;
continue;
}
for (int x = 0; x <= r; x++) {
int z = f[u-1+x][r-x];
if (z >= 0)
ret = max(ret, z + sco[x]);
}
}
}
return f[1][n-2]+sco[0];
}
No comments:
Post a Comment