Title: Give you some bricks, ask if you can be listed as 2 height of the same tower, each layer of a stone.
Analysis: DP, Twin Towers problem. and Lis, knapsack and other problems are the same, the first I item of the optimal sub-problem.
Status: F (i,j) for the first I material, the height of the tower (or the low tower) when the absolute value of the difference of two Towers is J;
Decision: There are 3 choices each time: Place on the tower, on the low tower, or not;
T = O (sum (h) *n) {Number of stages * sum of length/2}.
Description: To reduce memory use as a scrolling array with auxiliary arrays.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define MAX (A, b) (( a) > (b)? (a):(b)) int f[1001];int t[1001];int h[101];int Main () {int n,s; while (scanf ("%d", &n)! = EOF && N! =-1) {s = 0; for (int i = 1; I <= n; + + i) {scanf ("%d", &h[i]); s + = h[i]; } s/= 2; memset (f, 0, sizeof (f)); memset (t, 0, sizeof (t)); for (int i = 1; I <= n; + + i) {for (int j = 0; J <= S; + + j) if (t[J]) { f[j+h[i] = max (t[J]+h[i], f[j+h[i]]); f[ABS (h[i]-j)] = max (max (t[J], t[J]+h[i]-j), f[abs (h[i]-j)]); } f[h[i]] = max (h[i], f[h[i]); for (int j = 0; J <= S; + + j) f[J] = max (f[j], t[J]); for (int j = 0; J <= s; + + j) t[J] = f[J]; } if (f[0]) printf ("%d\n", f[0]); else printf ("sorry\n"); } return 0;}
Zoj 2059-the Twin Towers