Topic Links: Lightoj 1422
Problem Solving Ideas:
In fact, a glance at the past did not expect to be DP, but drew a connection diagram, that is, two of the same number with a straight line, the requirement is actually a longest non-interlaced sequence. Then came the thought of a symmetry, such as the example of "5 1 2 3 2 1", so there is no solution. But also because of the thought of this situation reminds me that this is an interval DP problem, so the solution is very simple.
Code:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define INF
0x3f3f3f3f using namespace std;
int n,dp[105][105],a[105];
int main () {int t,t=0;
scanf ("%d", &t);
while (t<t) {scanf ("%d", &n);
for (int i=1;i<=n;i++) {scanf ("%d", &a[i]);
} for (int i=1;i<=n;i++) for (int j=i;j<=n;j++) dp[i][j]=j-i+1;
for (int i=1;i<n;i++) dp[i][i+1]=2-(a[i]==a[i+1]);
for (int l=2;l<n;l++) {for (int i=1;i<=n-l;i++) {if (A[i]==a[i+l])
dp[i][i+l]=dp[i+1][i+l-1]+1;
for (int j=i;j<=i+l;j++) {dp[i][i+l]=min (dp[i][i+l], dp[i][j]+dp[j][i+l]-1);
}}} printf ("Case%d:%d\n", ++t,dp[1][n]);
} return 0; }
Summary:
It's a good question to turn a seemingly dynamic plan into a dynamic plan, quite magical.