标签:php 最长公共子串 math bsp stream short can using --
http://acm.hrbust.edu.cn/vj/index.php?c=problem-problem&id=20480
LCS求最长公共子串
#include<stdio.h> #include<iostream> #include<map> #include<string.h> #include<vector> using namespace std; short a[5005][5005]; char s1[5005]; char s2[5005]; int LCS(const char *s1, const char *s2) { // s1:0...m, s2:0...n int m = strlen(s1), n = strlen(s2); int i, j; a[0][0] = 0; for( i=1; i <= m; ++i ) a[i][0] = 0; for( i=1; i <= n; ++i ) a[0][i] = 0; for( i=1; i <= m; ++i ) for( j=1; j <= n; ++j ) { if(s1[i-1]==s2[j-1]) a[i][j] = a[i-1][j-1]+1; else if(a[i-1][j]>a[i][j-1]) a[i][j]= a[i-1][j]; else a[i][j] = a[i][j-1]; } return a[m][n]; } int main() { int n; while(~scanf("%d",&n)) { memset(s1,0,sizeof(s1)); memset(s2,0,sizeof(s2)); for(int i=0; i<n; i++) { cin>>s1[i]; } for(int i=0; i<n; i++) { s2[i]=s1[n-i-1]; } //cout<<s1<<" "<<s2<<endl; cout<<n-LCS(s1,s2)<<endl; } }
动态规划 注意short类型,不然会超内存;
#include<stdio.h> #include<iostream> #include<string.h> #include<math.h> using namespace std; short dp[5001][5001]; int main() { int k; char a[5001],b[5001]; while(~scanf("%d",&k)) { scanf("%s",a); int p=0; for(int i=k-1; i>=0; i--) { b[p]=a[i]; p++; } //for(int i=0; i<k; i++) // printf("%c%c",b[i],(i==(k-1))?‘\n‘:‘ ‘); memset(dp,0,sizeof(0)); for(int i=1; i<=k; i++) for(int j=1; j<=k; j++) { if(a[i]==b[j]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } // printf("%d\n",dp[k][k]); printf("%d\n",k-dp[k][k]); } }
标签:php 最长公共子串 math bsp stream short can using --
原文地址:https://www.cnblogs.com/RainzzZ/p/12067054.html