-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtry.cpp
83 lines (65 loc) · 1.49 KB
/
try.cpp
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
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<vector<int>> dp;
void display(vector<vector<int>> dp) {
for(auto row : dp) {
for(auto element : row) {
cout << element << " ";
}
cout << endl;
}
}
int f(string A, string B, int i, int j) {
for(int i = A.size()-1; i >= 0; i--) {
for(int j = B.size()-1; j >= 0; j--) {
if(A[i] == B[j]) {
dp[i][j] = 1 + dp[i+1][j+1];
}
else {
dp[i][j] = max(dp[i+1][j], dp[i][j+1]);
}
}
}
return dp[0][0];
}
void printLCS(string A, string B) {
int i = 0;
int j = 0;
int n = A.size();
int m = B.size();
while(i <= n and j <= n) {
if(dp[i][j] == 0) {
break;
}
if(dp[i][j] == max(dp[i+1][j], dp[i][j+1])) {
if(dp[i+1][j] > dp[i][j+1]) {
i++;
}
else j++;
}
else if(dp[i][j] == 1 + dp[i+1][j+1]) {
cout << A[i];
i++, j++;
}
}
}
int main() {
string text_1 = "bbcbcaabc";
string text_2 = "cacaabaaaa";
int n = text_1.length();
int m = text_2.length();
dp.clear();
dp.resize(n+1, vector<int> (m+1,0));
int lengthofLCS = f(text_1, text_2, 0, 0);
cout << lengthofLCS << endl;
display(dp);
printLCS(text_1,text_2);
cout << endl;
}
/*
s1 = abracadabra
s2 = avadakedavra
*/
// ans -> aaadara