码迷,mamicode.com
首页 > 其他好文 > 详细

[dp]LCS最长公共子序列

时间:2017-05-13 13:39:07      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:names   序列   判断   bit   ==   path   course   blog   html   

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

复杂度:${\rm 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 }

 

[dp]LCS最长公共子序列

标签:names   序列   判断   bit   ==   path   course   blog   html   

原文地址:http://www.cnblogs.com/elpsycongroo/p/6848587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!