ADFRUITS-Advanced Fruits
#include <iostream>
using namespace std;
int dp[101][101];
char str[202];
int main()
{
string a, b;
int l1, l2, i, j;
while(cin >> a >> b)
{
l1 = a.size();
l2 = b.size();
//max length of common substring
for(i = 0; i <= l1; i++)
{
for(j = 0; j <= l2; j++)
{
if(i == 0 || j == 0)
dp[i][j] = 0;
else
{
if(a[i - 1] == b[j - 1])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else
{
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
}
int index = dp[l1][l2];
char lcs[index + 1];
lcs[index] = '\0';
index--;
i = l1, j = l2;
//stores the common sub string in lcs array
while(i > 0 && j > 0)
{
if(a[i - 1] == b[j - 1])
{
lcs[index] = a[i - 1];
i--, j--,index--;
}
else
{
if(dp[i - 1][j] > dp[i][j - 1])
{
i--;
}
else
j--;
}
}
for(i = 0; i <= l1 + l2; i++)
{
str[i] = '\0';
}
i = j = index = 0;
int k = 0;
while(lcs[index])
{
while(a[i] != lcs[index] || b[j] != lcs[index])
{
if(a[i] != lcs[index] && i < l1)
{
str[k++] = a[i];
i++;
}
if(b[j] != lcs[index] && j < l2)
{
str[k++] = b[j];
j++;
}
}
str[k++] = lcs[index];
index++, i++, j++;
}
if(i < l1)
{
while(i < l1)
{
str[k++] = a[i++];
}
}
if(j < l2)
{
while(j < l2)
{
str[k++] = b[j++];
}
}
cout << str << endl;
}
return 0;
}
Comments
Post a Comment