The question is that at least one string can be divided into several paragraphs, so that each paragraph is a palindrome string.
At first, the direct interval dp,dp[i][j] represents the answer of the substring [i,j], but the length of the string 1000,100w state, a state is transferred from multiple states, and when it is transferred, it is enumerated so that time complexity is not feasible.
And then I thought about dimensionality, only linear dp,dp[i] represents the answer to a substring [0,i]. This can be transferred from I-1 to I,str[i] alone to make a section or Str[i] can and the preceding composition palindrome string, the equation is as follows:
Dp[i]=min (dp[i-1]+1,dp[j-1]+1) (sub-string [J,i] is a palindrome string)
The question now is how to quickly determine if any substring of a string is a palindrome string.
I guess it's not going to use some data structures or algorithms for strings. Suddenly think of interval DP, this problem can be solved with interval DP:
DP2[I][J] Indicates whether the substring [i,j] is a palindrome
The transfer can be as long as one step:
DP2[I][J] = (Str[i]==str[j] && dp2[i+1][j-1])
So this can be done in O (strlen2) preprocessing and in the O (1) Time complexity to determine whether any interval is a palindrome string.
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 Charstr[1111];6 BOOLpalindrome[1111][1111];7 intd[1111];8 intMain () {9 intT;Tenscanf"%d",&t); One for(intCse=1; cse<=t; ++CSE) { Ascanf"%s", str); - intn=strlen (str); - the for(intI=0; i<n; ++i) { - for(intj=0; j<n; ++j) { -Palindrome[i][j]= (i>=j); - } + } - for(intlen=2; len<=n; ++Len) { + for(intI=0; i+len<=n; ++i) { A if(str[i]==str[i+len-1] && palindrome[i+1][i+len-2]) palindrome[i][i+len-1]=1; at } - } - -d[0]=1; - for(intI=1; i<n; ++i) { - if(palindrome[0][i]) { ind[i]=1; - Continue; to } +d[i]=d[i-1]+1; - for(intj=i-1; j>=1; --j) { the if(Palindrome[j][i]) d[i]=min (d[i],d[j-1]+1); * } $ }Panax Notoginsengprintf"Case %d:%d\n", cse,d[n-1]); - } the return 0; +}
LightOJ1044 palindrome Partitioning (interval dp+ linear DP)