标签:
http://acm.nyist.net/JudgeOnline/problem.php?pid=36
2 asdf adfsd 123abc abc123abc
3 6
我的弱弱的代码:
#include <fstream> #include <iostream> #include <cstdio> #include <cstring> using namespace std; const int INF=0x7fffffff; const int N=1005; char s1[N],s2[N]; int dp[N][N]; int main() { //freopen("D:\\input.in","r",stdin); //freopen("D:\\output.out","w",stdout); int n; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%s %s",s1+1,s2+1); int l1=strlen(s1+1); int l2=strlen(s2+1); dp[0][0]=0; dp[1][0]=0; dp[0][1]=0; for(int i=1;i<=l1;i++){ for(int j=1;j<=l2;j++){ if(s1[i]==s2[j]){ dp[i][j]=1+dp[i-1][j-1]; }else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } printf("%d\n",dp[l1][l2]); } return 0; }
一位coder的代码,加了空间优化:
#include <stdio.h> #include <string.h> char s1[1001], s2[1001]; int dp[1001], t, old, tmp; int main(){ scanf("%d", &t); getchar(); while(t--){ gets(s1); gets(s2); memset(dp, 0, sizeof(dp)); int lenS1=strlen(s1), lenS2=strlen(s2); for(int i=0; i<lenS1; i++){ old=0; //若s1[i]==s2[j], dp[i][j] = dp[i-1][j-1]+1 //否则,dp[i][j] = max(dp[i-1][j], dp[i][j-1]) //此处进行了空间优化,old 代表 dp[i-1][j-1] //dp[j-1] 代表 dp[i][j-1], dp[j] 代表 dp[i-1][j] for(int j=0; j<lenS2; j++){ tmp = dp[j]; if(s1[i]==s2[j]) dp[j] = old+1; else if(dp[j-1]>dp[j])dp[j]=dp[j-1]; old = tmp; } } printf("%d\n", dp[lenS2-1]); } return 0; }
另一位牛人写的代码,加了时间优化,足足缩短了10倍的时间消耗:
#include <stdio.h> #include <cstring> #include <iostream> #include <vector> #include <algorithm> using namespace std; int n,m; const int CHAR = 256; const int maxn = 1010; int ans[maxn*maxn]; int dp[maxn*maxn]; char S[maxn]; vector<int>v[CHAR]; int er(int l,int r,int x) { while(l<=r) { int mid = (l+r)/2; if( ans[mid] >= x ) r = mid - 1; else l = mid + 1; } return l; } int main() { scanf("%d",&n); while( n-- ) { for(int i=0 ; i<CHAR ; i++) v[i].clear(); scanf("%s",S); int l = strlen(S); for(int i=l-1 ; i>=0 ; i-- ) { v[ S[i] ].push_back(i); ///S[i]字符在字符串对应的位置 ///cout << S[i] << " " << v[ S[i] ].size() << endl; } int x = 0; scanf("%s",S); l = strlen(S); for(int i=0 ; i<l ; i++ ){ int k = v[ S[i] ].size(); if( k ) { for(int j=0 ; j<k ; j++ ) { dp[x++] = v[ S[i] ][j]; } } } m = 0; ans[m] = -1<<30; for(int i=0; i<x ; i++) { int x = er(0,m,dp[i]); ans[x] = dp[i]; if( x == m+1 ) m++; } printf("%d\n",m); } return 0; }
标签:
原文地址:http://www.cnblogs.com/jiu0821/p/4518634.html