The longest common subsequence (dp, c++)

topic:

Description: Given two strings A and B, find a string that is the common part of A and B (the common part can be discontinuous).

Solution: dp, open a two-dimensional array dp[i][j], representing the longest common subsequence of a[1] to a[i] and b[1] to b[j], for example, when a is "story" When b is "sbtar", dp[2][3] means that st and sbt are compared, and the longest is st, so it is equal to 2. It is probably this chart:Insert picture description here

Then when a[i]==b[j], dp[i][j]=dp[i-1][j-1], because if the current letters are not equal then the two strings must be added to the current two The longest subsequence of the letters is the same.
So when a[i]!=b[j], dp[i][j]=max(dp[i-1][j], dp[i][j-1]), which means equal to a character String minus one or b string minus the maximum value of the longest subsequence of the last letter (it's amazing).

Complete code:

#include<algorithm>
#include<iostream>
#include<string.h>
using namespace std;
char a[100];
char b[100];
int dp[101][101];


int main()
{
    
    
	cin >> a >> b;
	int la = strlen(a);
	int lb = strlen(b);
	memset(dp, 0, sizeof dp);		//初始化0,因为第0个元素没有最长子序列,而且dp[1][1]之类的也要用到
	for (int i = 1; i <= la; i++)
		for (int j = 1; j <= lb; j++)
		{
    
    
			if (a[i] == b[j]) dp[i][j] = dp[i - 1][j - 1] + 1;
			else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
		}
	cout << dp[la][lb];		//遍历到dp[i][j]是最大值
	return 0;
}

Afterword: I don't like colds, and the efficiency is extremely low

Guess you like

Origin blog.csdn.net/Kyrie_irving_kun/article/details/114993637