-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest common subsequence - DP.cpp
91 lines (73 loc) · 1.66 KB
/
Longest common subsequence - DP.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
84
85
86
87
88
89
90
91
// Dynamic programming solution
#include <bits/stdc++.h>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
using ld = long double;
using llint = long long;
using ullint = unsigned long long;
using pii = pair <int,int>;
using pcc = pair <char,char>;
using pss = pair <string,string>;
using vi = vector <int>;
using vb = vector <bool>;
using vii = vi::iterator;
#define INF (1<<30)
#define MOD 1000000007
#define mp make_pair
#define mt make_tuple
#define all(c) c.begin(), c.end()
#define ms(name,val) memset(name, val, sizeof name)
#define np nullptr
int n, m;
vi a, b;
vector <vi> DP;
void longestCommonSubsequence()
{
DP.resize(n+1);
for (int t1 = 0; t1 <= n; ++t1)
DP[t1].resize(m+1);
for (int t1 = 1; t1 <= n; ++t1)
{
for (int t2 = 1; t2 <= m; ++t2)
{
DP[t1][t2] = max(DP[t1-1][t2], DP[t1][t2-1]);
if (a[t1-1] == b[t2-1])
DP[t1][t2] = max(DP[t1][t2], (1 + DP[t1-1][t2-1]));
}
}
vi ans;
int x = n, y = m;
while (x && y)
{
if (a[x-1] == b[y-1])
{
ans.push_back(a[x-1]);
--x, --y;
}
else
{
if (DP[x][y-1] > DP[x-1][y])
--y;
else
--x;
}
}
for (int t1 = ans.size()-1; t1 >= 0; --t1)
cout << ans[t1] << ' ';
cout << '\n';
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
a.resize(n);
b.resize(m);
for (int t1 = 0; t1 < n; ++t1)
cin >> a[t1];
for (int t1 = 0; t1 < m; ++t1)
cin >> b[t1];
longestCommonSubsequence();
return 0;
}