Description assume that you have a 5-length block that has not been painted in any color at the beginning. You want to apply its 5 unit lengths to red, green, blue, green, and red, using a string of length 5 to indicate this target: RGBGR. Each time you can paint a continuous piece of wood into a given color, the color of the coat is covered with the first color. For example, for the first time, the wood planks were painted rrrrr, the second painted Rgggr, the third painted rgbgr, to achieve the goal. Achieve your goals with as few coloring times as possible. Input enters only one row, containing a string of length n, which is the coloring target. Each character in a string is an uppercase letter, different letters represent different colors, and the same letters represent the same color. Output has only one row, which contains a single number, which is the minimum number of paint times. Sample Inputsample Output"Sample Input 1"
AAAAA
"Sample Input 1"
Rgbgr
"Sample Output 1"
1
"Sample Output 1"
3
HINT
40% of the data meet: 1<=n<=10
100% of the data meet: 1<=n<=50
Solution: The basic idea is the enumeration interval f[i][j] to indicate to properly apply i--j this interval minimum need a few strokes, and then enumerate a k, the interval is divided into f[i][k],f[[k+1][j] two parts, F[i][j]=min (f[i][j],f[i][k]+f[k+ 1][J].
But here is a special case, because each lattice can be repeatedly painted, so there will be a special sentence, with A[i] to store the color of the I lattice, if a[i]=a[j], we can initially choose to use a pen to paint them, so there is a special transfer equation: F[i][j]=min (f[ I+1][J],F[I][J-1],F[I+1][J-1]+1);
It means that there are three options: 1. When the i+1--j is painted, the a[i] has been painted, 2. When the i--j-1 is painted, the a[j] has been painted, 3. Put the a[i]a[j in the first place, and then consider the inside.
Well, look at the specific procedure.
#include <iostream>#include<cstdio>#include<string>#include<algorithm>using namespacestd;intj,n,f[ -][ -];stringS1;Chars[ +];intMain () {CIN>>S1; N=s1.size (); for(intI=1; i<=n;i++) s[i]=s1[i-1]; for(intI=0; i<=n+1; i++) for(intj=0; j<=n+1; j + +) if(I==J) f[i][j]=1; Elsef[i][j]=21000000; for(intlen=2; len<=n;len++) for(intI=1; i<=n-len+1; i++) {J=i+len-1; if(S[i]==s[j])//The same thing at both ends .{F[i][j]=min (f[i-1][j],f[i][j-1]); if(len==2) f[i][j]=1;//If the two sides are adjacent, apply a pen. ElseF[i][j]=min (f[i][j],f[i-1][j-1]+1);//otherwise judgment } Else { for(intk=i;k<=j-1; k++) F[i][j]=min (f[i][j],f[i][k]+f[k+1][J]);//break the interval to discuss}} cout<<f[1][n]<<Endl; return 0;}
1260: [CQOI2007] Coloring Paint