-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLCS.cpp
More file actions
62 lines (51 loc) · 1.2 KB
/
Copy pathLCS.cpp
File metadata and controls
62 lines (51 loc) · 1.2 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
//Problem : https://atcoder.jp/contests/dp/tasks/dp_f
#include <bits/stdc++.h>
#define int long long
#define sz(x) (int)(x.size())
using namespace std;
const int N = 3e3 + 5, inf = 1e18, mod = 1e9 + 7;
int n, m, maxLen, dp[N][N];
string s, t;
int go(int id1, int id2){
if(id1 >= n || id2 >= m)
return 0;
int& ans = dp[id1][id2];
if(~ans)
return ans;
int c1 = 0;
if(s[id1] == t[id2])
c1 = max(c1, 1 + go(id1 + 1, id2 + 1));
int c2 = go(id1 + 1, id2);
int c3 = go(id1, id2 + 1);
return ans = max({c1, c2, c3});
}
void find(int i, int j){
if(i >= n || j >= m)
return;
int actual = go(i, j);
int c1 = 0;
if(s[i] == t[j]){
c1 = 1 + go(i + 1, j + 1);
if(actual == c1){
cout << s[i];
return find(i + 1, j + 1);
}
}
int c2 = go(i + 1, j);
if(actual == c2){
return find(i + 1, j);
}
int c3 = go(i, j + 1);
if(actual == c3){
return find(i, j + 1);
}
}
int32_t main(){
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
memset(dp, -1, sizeof(dp));
cin >> s >> t;
n = sz(s), m = sz(t);
maxLen = go(0,0);
find(0, 0);
}