-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlongestcommon.cpp
More file actions
71 lines (65 loc) · 1.49 KB
/
longestcommon.cpp
File metadata and controls
71 lines (65 loc) · 1.49 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
#include<bits/stdc++.h>
using namespace std;
#define lli long long int
#define MOD 1000000007
void CowboyBebop(){
string s1, s2 ;
cin >> s1 >> s2 ;
int m = s1.length() ;
int n = s2.length() ;
int c[m+1][n+1] ;
int d[m+1][n+1] ;
for(int i = 0 ; i < m +1 ; i++){
for(int j = 0 ; j < n+1 ; j++){
c[i][j] = 0 ;
d[i][j] = 0 ;
}
}
for (int i = 0; i <= m; i++){
for (int j = 0; j <= n; j++){
if (i == 0 || j == 0){
c[i][j] = 0;
d[i][j] = 0 ;
}
else if (s1[i - 1] == s2[j - 1]) {
c[i][j] = c[i - 1][j - 1] + 1;
d[i][j] = 3 ;
}
else{
c[i][j] = max(c[i - 1][j], c[i][j - 1]);
if(c[i - 1][j] >= c[i][j - 1]) {d[i][j] = 1; }
else {d[i][j] = 2 ;}
}
}
}
string s ;
int i = m , j = n ;
while (c[i][j]){
if(d[i][j] == 3 ){
s = s + (s1[i-1]);
i--;
j--;
}
else if (d[i][j] == 2){
j--;
}
else{
i--;
}
}
reverse(s.begin(),s.end());
cout<<s<<endl;
}
using namespace std;
int main(void){
std::ios_base::sync_with_stdio(false);
// #ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int t = 1;
//cin >> t;
while(t--){
CowboyBebop();
}
return 0;
}