Portal
Problem-solving ideas
It is clear that the board of the longest common subsequence (LCS) of.
Definition: represents the longest common subsequence S1 and the first j bits before i S2 with bits dp [i] [j].
State transition:
- 当s1[i]==s2[j]时,dp[i][j]=dp[i-1][j-1]+1;
- 当s1[i]!=s2[j]时,dp[i][j]=max(dp[i-1][j],dp[i][j-1];
Obviously right.
Bold conjecture without proof!
Plus one equal in time, the results will not be poor than without, so can be a plus.
Time complexity: O (n- 2 ).
AC Code
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 string s1,s2; 5 int l1,l2,dp[10005][10005]; 6 int main() 7 { 8 cin>>s1>>s2; 9 l1=s1.length(); 10 l2=s2.length(); 11 for(int i=1;i<=l1;i++){ 12 for(int j=1;j<=l2;j++){ 13 if(s1[i-1]==s2[j-1]) dp[i][j]=dp[i-1][j-1]+1; 14 else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 15 } 16 } 17 cout<<dp[l1][l2];; 18 return 0; 19 }
//AHOI2004 Day1t1