Title: 【POJ1159】Palindrome
This question is a relatively watery DP question.
We can use f[i][j] to denote the minimum number of letters needed to turn the interval [i..j] into a palindrome, so we can easily get the state transition equation:
At the time of this s [i] == s [j], f [i] [j] = min {f [i + 1] [j-1], f [i + 1] [j] + 1, f [i ] [j-1] +1}; When this s [i]! = S [j], f [i] [j] = min {f [i + 1] [j] + 1, f [i] [ j-1] +1}
This gives the code:
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<cmath> #define min(x,y) (x<y?x:y) #define N 5000 using namespace std; int n,f[N+5][N+5]; string s; intmain() { scanf("%d",&n),cin>>s; for(int i=n-1;i>=0;i--) for(int j=i+1;j<n;j++) if(s[i]==s[j]) f[i][j]=min(f[i+1][j-1],min(f[i+1][j],f[i][j-1])+1);else f[i][j]=min(f[i+1][j],f[i][j-1])+1;//DP过程 printf("%d",f[0][n-1]); return 0; }
However, such code will exceed memory, what should we do?
We can change the type of the f[][] array to short int, so that there is enough memory (of course, we can also use the array for rolling storage):
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<cmath> #define min(x,y) (x<y?x:y) #define N 5000 using namespace std; int n; short f[N+5][N+5]; string s; intmain() { scanf("%d",&n),cin>>s; for(int i=n-1;i>=0;i--) for(int j=i+1;j<n;j++) if(s[i]==s[j]) f[i][j]=min(f[i+1][j-1],min(f[i+1][j],f[i][j-1])+1);else f[i][j]=min(f[i+1][j],f[i][j-1])+1; printf("%d",f[0][n-1]); return 0; }
Copyright statement: Please indicate the address for reprinting