sample solution

advertisement
Homework # 25 sample solution:
8-11
Suppose a[1..n] is an array of n numbers, in order to form a circle, we will
copy the subarray a[1 … n-1] to the end of a[1..n] to obtain an array of N= 2n – 1
numbers.
First we compute the optimal sum A[i] of the subarray ending at a[1..i]:
A[i] = max { A[i-1] + a[i], 0 }
Now, the maximal sum can be computed as:
BestSum = max {A[i] | 1 <= i <= N}
Max_Sum(a[], n ){
// since we only need B[n-1] and A[n-1] (not all earlier values)
// we could just use two variables
max_sum = 0;
current_max = 0;
count = 0;
}
for(int i = 1; i < 2n; i++){
current_max = current_max + a[i%n];
count++;
if (count > n) { current_max = current_max – a[i% - 1]; count--; }
if (current_max < 0) current_max = 0;
if (current_max == 0) count = 0;
max_sum = max{max_sum, current_max};
}
return max_sum;
The time complexity of the algorithm is O(n).
8-12
Suppose we want to divide numbers from 1 to n according to some given breaking
points. Let cuts[] be the given breaking point array such that cuts[1] < … < cuts[m]
are breaking points. We also add two boundary points, 1 and n, to the array cuts:
cuts[0] = 1 and cuts[m+1] = n. Let OPT(i, j) be the minimal cost for the points
between cuts[i] and cuts[j]. Then the minimal cost of breaking points from 1 to n
according to the given breaking points will be OPT(0, m+1).
The recurrence relation is:
OPT(i, j) = min(OPT(i, k) + OPT(k+1, j) + (cuts[j]-cuts[i] +1)) ( i< k < j)
and
OPT(i,i) = 1; OPT(i,i+1) = cuts[i+1] – cuts[i] + 1
We will use a two-dimensional array M to record OPT(i,j), i.e., M[i,j] = OPT(i,j). We
may design the following algorithm to compute the min cost, following the
recurrence relation of OPT(i,j).
Compute_Min_Cost (int n, int cuts[], int m) {
cuts[0] = 1; cuts[m+1] = n;
for (int i = 0; i <= m; i++)
for (int j = i+1; j <= m+1; j++) M[i,j] = -1; // -1 means undefined.
return Min_cost(cuts, 0, m+1);
}
Min_Cost(int cuts[], int i, int j)
{
int totalCost = j – i + 1;
if (j == i) return 1;
if (j == i+1) return totalCost;
if (M[i,j] != -1) return M[i,j];
int cost = MAX_INT;
for(int k= i+1; k<j; k++) {
int t = Min_Cost (cuts, i, k) + Min_Cost (cuts, k+1, j);
if ( t < cost ) cost = t;
}
M[i,j] = cost + totalCost;
return M[i,j];
}
The space and time complexity is O(m2).
Download