-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCS.cpp
36 lines (27 loc) · 787 Bytes
/
LCS.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
#include <bits/stdc++.h>
using namespace std;
#define long long long int
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string s, t;
cin >> s >> t;
int n = s.size(), m = t.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
if (s[i - 1] == t[j - 1])
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
string ans = "";
int i = n, j = m;
while (i && j) {
if (dp[i][j] == dp[i - 1][j]) i--;
else if (dp[i][j] == dp[i][j - 1]) j--;
else ans += s[--i], j--;
}
reverse(ans.begin(), ans.end());
cout << ans << "\n";
}