1. 程式人生 > >【51nod】---1006 最長公共子序列Lcs(動態規劃&&字串LCS)

【51nod】---1006 最長公共子序列Lcs(動態規劃&&字串LCS)

題目連結這裡呀
1006 最長公共子序列Lcs
基準時間限制:1 秒 空間限制:131072 KB 分值: 0 難度:基礎題 收藏 關注
給出兩個字串A B,求A與B的最長公共子序列(子序列不要求是連續的)。
比如兩個串為:

abcicba
abdkscab

ab是兩個串的子序列,abc也是,abca也是,其中abca是這兩個字串最長的子序列。
Input
第1行:字串A
第2行:字串B
(A,B的長度 <= 1000)
Output
輸出最長的子序列,如果有多個,隨意輸出1個。
Input示例
abcicba
abdkscab
Output示例
abca

分析:注意哦,子序列不是子段,子序列可以是不連續的。
求最長公共子序列(LCS)用動態規劃。
兩字串str1,str2,用dp[i][j]表示str1[1]~str1[i]和str2[1]~str2[j]兩個子段最長公共子序列的長度。
若str1[i]==str2[j],那麼此時的LCS長度就相當於在(i-1,j-1)的LCS長度上加1,即dp[i][j]=dp[i-1][j-1]+1;
若str1[i]!=str2[j],此時的LCS長度應取(i-1,j)和(i,j-1)的較大者,因為要求最長嘛!即dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
所以,dp[i][j]={ dp[i-1][j-1]+1; (str1[i]==str2[j])
max(dp[i-1][j],dp[i][j-1];(str1[i]!=str2[j])
}
dp[len1][len2]即為LCS長度;
若要求出LCS,還需要用到棧的資料結構哦。
用兩個‘指標’ant1,ant2倒序指向兩字串中的字元,
若str1[ant1]==str1[ant2],則入棧(任一個就行哦),同時ant1–,ant2–;
若不相等,肯定首先字元不能入棧了哦,那麼兩個‘指標’怎麼辦呢?
兩種情況:
如果dp[ant1-1][ant2]>dp[ant1][ant2-1],說明(ant1-1,ant2)這一部分的LCS比(ant1,ant2-1)的要長哦,那麼當然就要研究看str1[ant1-1]和str1[ant2]是否相等咯,也就是ant1–,前移;
否則,ant2–。
LCS的全部字元入棧後,再依次輸出。
程式碼如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAX_N 1000
#include<stack>
int dp[MAX_N+11][MAX_N+11];
char str1[MAX_N+11],str2[MAX_N+11];
int main()
{
    scanf("%s %s",str1+1,str2+1);
    memset(dp,0,sizeof(dp));
    str1[0]='0';
    str2[0]='0'
; int len1=strlen(str1)-1; int len2=strlen(str2)-1; int ans=0; int i,j; for(i=1;i<=len1;i++) { for(j=1;j<=len2;j++) { if(str1[i]==str2[j]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1
]); } ans=max(ans,dp[i][len2]);//更新為當前最長,最後得出全部最長 } int ant1=len1; int ant2=len2; stack<char> stk; while(ant1>0&&ant2>0) { if(str1[ant1]==str2[ant2])//若對應兩字元相等,說明是LCS組成部分,入棧 { stk.push(str1[ant1]); ant1--; ant2--; } else if(dp[ant1-1][ant2]>dp[ant1][ant2-1]) ant1--; else ant2--; } while(!stk.empty() ) { printf("%c",stk.top()); stk.pop() ; } printf("\n"); return 0; }