1 //Accepted 204 KB 891 ms 2 //dp最长公共子串 3 //dp[i][j]=max(dp[i-1][j],dp[i][j-1]) 4 //dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1) (s1[i]==s2[j]) 5 #include <cstdio> 6 #include <cstring> 7 #include <iostream> 8 using namespace std; 9 const int imax_n = 5002; 10 int dp[2][imax_n]; 11 char s1[imax_n]; 12 char s2[imax_n]; 13 int n; 14 int max(int a,int b) 15 { 16 return a>b?a:b; 17 } 18 void Dp() 19 { 20 memset(dp,0,sizeof(dp)); 21 for (int i=1;i<=n;i++) 22 { 23 for (int j=1;j<=n;j++) 24 { 25 dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]); 26 if (s1[i-1]==s2[j-1]) 27 dp[i%2][j]=max(dp[i%2][j],dp[(i-1)%2][j-1]+1); 28 } 29 } 30 printf("%d\n",n-dp[n%2][n]); 31 } 32 int main() 33 { 34 while (scanf("%d",&n)!=EOF) 35 { 36 scanf("%s",s1); 37 for (int i=0;i<n;i++) 38 s2[i]=s1[n-1-i]; 39 s2[n]=‘\0‘; 40 Dp(); 41 } 42 return 0; 43 }
poj1159 dp最长公共子串
时间: 2024-11-06 03:56:39