-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAdvanced_Fruits.cpp
More file actions
72 lines (64 loc) · 1.53 KB
/
Advanced_Fruits.cpp
File metadata and controls
72 lines (64 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//https://www.spoj.com/problems/ADFRUITS/
/*
Approach :
First we will find the LCS of the two strings.
We will insert the non-LCS characters in the LCS found above in their original order.
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str1, str2;
while(cin >> str1)
{
cin >> str2;
int m = str1.length(), n = str2.length();
int LCS[m+1][n+1];
for(int i = 0; i <= m; i++)
{
for(int j = 0; j <= n; j++)
{
if(i == 0 || j == 0)
LCS[i][j] = 0;
else if(str1[i-1] == str2[j-1])
LCS[i][j] = 1 + LCS[i-1][j-1];
else
LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1]);
}
}
int i = m, j = n;
string result = "";
while(i > 0 && j > 0)
{
if(str1[i-1] == str2[j-1])
{
result += str1[i-1];
i--;
j--;
}
else if(LCS[i-1][j] > LCS[i][j-1])
{
result += str1[i-1];
i--;
}
else
{
result += str2[j-1];
j--;
}
}
while(i > 0)
{
result += str1[i-1];
i--;
}
while(j > 0)
{
result += str2[j-1];
j--;
}
reverse(result.begin(), result.end());
cout << result << endl;
}
return 0;
}