[dp]LCS最长公共子序列

https://www.51nod.com/tutorial/course.html#!courseId=4

复杂度:${ m O}(nm)$

转移方程:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 int n,m;
 5 int dp[1002][1002];
 6 char path[1002];
 7 string s,t;
 8 int main(){
 9     cin>>s>>t;
10     n=s.size();
11     m=t.size();
12     for(int i=0;i<n;i++){
13         for(int j=0;j<m;j++){
14             if(s[i]==t[j]) dp[i+1][j+1]=dp[i][j]+1;//判断条件一定看清楚 
15             else dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
16         }
17     }
18     stack<char>ss;
19     int i=n,j=m;
20     while(dp[i][j]){
21         if(dp[i][j]==dp[i-1][j]) i--;
22         else if(dp[i][j]==dp[i][j-1]) j--;
23         else{
24             ss.push(s[i-1]);
25             i--,j--;
26         }
27     }
28     while(!ss.empty()){
29         printf("%c",ss.top());
30         ss.pop();
31     }
32     return 0;
33 }
原文地址:https://www.cnblogs.com/elpsycongroo/p/6848587.html