Example 1: longest common subsequence codefroces
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1001;
int dp[MAX][MAX];
bool visited[MAX][MAX];
int x, y;
string s1, s2;
int lcs(int i, int j)
{
if(i == x || j == y)
return 0;
if(visited[i][j])
return dp[i][j];
visited[i][j] = true;
int ans = 0;
if(s1[i] == s2[j])
{
ans = max(ans, 1+lcs(i+1, j+1));
}
else
{
ans = max(ans, lcs(i+1, j));
ans = max(ans, lcs(i, j+1));
}
dp[i][j] = ans;
return ans;
}
int main()
{
cin >> x >> y;
cin >> s1 >> s2;
for(int i=0; i<=x; i++)
{
for(int j=0; j<=y; j++)
{
visited[i][j] = false;
}
}
cout << lcs(0, 0);
return 0;
}
Example 2: longest increasing subsequence when elements hae duplicates
#include <iostream>
#include <algorithm>
using namespace std;
#define N 20
int lookup[N][N];
void LCS(int X[], int Y[], int m, int n)
{
if (m == 0 || n == 0)
return;
if (X[m - 1] == Y[n - 1])
{
LCS(X, Y, m - 1, n - 1);
cout << X[m - 1] << " ";
return;
}
if (lookup[m - 1][n] > lookup[m][n - 1])
LCS(X, Y, m - 1, n);
else
LCS(X, Y, m, n - 1);
}
void findLCS(int X[], int Y[], int m, int n)
{
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (X[i - 1] == Y[j - 1])
lookup[i][j] = lookup[i - 1][j - 1] + 1;
else
lookup[i][j] = max(lookup[i - 1][j], lookup[i][j - 1]);
}
}
LCS(X, Y, m, n);
}
int removeDuplicates(int X[], int n)
{
int k = 0;
for (int i = 1; i < n; i++)
if (X[i] != X[k])
X[++k] = X[i];
return k + 1;
}
void findLIS(int X[], int n)
{
int Y[n];
for (int i = 0; i < n; i++)
Y[i] = X[i];
sort(Y, Y + n);
int m = removeDuplicates (Y, n);
findLCS(X, Y, n, m);
}
int main()
{
int X[] = { 100,1,100,1,100 };
int n = sizeof(X)/sizeof(X[0]);
cout << "The LIS is ";
findLIS(X, n);
return 0;
}