标签:io os ar for sp 问题 bs amp ef
这个题是走弯路了,刚开始自己DP出了方程,无限MLE,唉
if(s1[i]==s1[j])
dp[i][j]=dp[i+1][j-1];
else dp[i][j]=min(dp[i][j-1],dp[i+1][j]) +1;
后来百度了一下,这个原来是个经典回文串问题,即先将串置反,然后求LCS........
然后就是这题卡时间卡的特别厉害,多用了一次strlen就TLE
AC:
#include<cstdio> #include<string> #include<string.h> #include<iostream> #include<algorithm> #include<map> #include<iterator> using namespace std; #define N 10+5000 #define max(a,b) ((a)>(b)?(a):(b)) int n,m; char s1[N],s2[N]; int dp[2][N]; int main() { int i; int T; //freopen("in.txt","r",stdin); while(~scanf("%d",&n)) { scanf("%s",s1); strcpy(s2,s1); strrev(s2); memset(dp,0,sizeof(dp)); int p=0; for(i=0;i<n;i++) { p=1-p; for(int j=0;j<n;j++) { if(s1[i]==s2[j]) dp[p][j+1]=dp[1-p][j]+1; else dp[p][j+1]=max(dp[p][j],dp[1-p][j+1]); } } printf("%d\n",n-dp[p][n]); } return 0; }
MLE:
#include<cstdio> #include<string> #include<string.h> #include<iostream> #include<algorithm> #include<map> #include<iterator> using namespace std; #define N 100+5000 #define mem(a) memset(a,0,sizeof(a)) #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) int n,m; char s1[N]; int dp[N][N]; int main() { int i,j,k; int T; //freopen("in.txt","r",stdin); while(~scanf("%d",&n)) { mem(dp); for(i=1;i<=n;i++) cin>>s1[i]; for(i=1;i<n;i++) if(s1[i]!=s1[i+1]) dp[i][i+1]=1; for(int len=2;len<=n;len++) for(i=1,j=i+len;j<=n;i++,j++) { if(s1[i]==s1[j]) dp[i][j]=dp[i+1][j-1]; else dp[i][j]=min(dp[i][j-1],dp[i+1][j]) +1; } printf("%d\n",dp[1][n]); } return 0; }
标签:io os ar for sp 问题 bs amp ef
原文地址:http://blog.csdn.net/gg_gogoing/article/details/40680845