-
Notifications
You must be signed in to change notification settings - Fork 0
/
最长公共子序列.cpp
71 lines (67 loc) · 1.31 KB
/
最长公共子序列.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
//最长公共子序列
#include<iostream>
#include<string>
using namespace std;
int cnt = 0;
void Sequence(int** b, int i, int j, string x, string y) {
if (i == 0 || j == 0) {
return;
}
if (b[i][j] == 0) {
Sequence(b, i - 1, j - 1, x, y);
//cout << x[i - 1];
cnt++;
}
else if (b[i][j] == 1) {
Sequence(b, i - 1, j, x, y);
}
else {
Sequence(b, i, j - 1, x, y);
}
}
int main() {
string x, y;
cin >> x >> y;
int xlen = x.length();
int ylen = y.length();
int** c = new int* [xlen + 1];
int** b = new int* [xlen + 1];
for (int i = 0; i <= xlen; i++) {
c[i] = new int[ylen + 1];
b[i] = new int[ylen + 1];
}
for (int i = 0; i <= xlen; i++) {
c[i][0] = 0;
b[i][0] = 0;
}
for (int j = 0; j <= ylen; j++) {
c[0][j] = 0;
b[0][j] = 0;
}
// 0-> ↖ 1->↑ 2->←
for (int i = 1; i <= xlen; i++) {
for (int j = 1; j <= ylen; j++) {
if (x[i - 1] == y[j - 1]) {
c[i][j] = c[i - 1][j - 1] + 1;
b[i][j] = 0;
}
else if (c[i - 1][j] >= c[i][j - 1]) {
c[i][j] = c[i - 1][j];
b[i][j] = 1;
}
else {
c[i][j] = c[i][j - 1];
b[i][j] = 2;
}
}
}
Sequence(b, xlen, ylen, x, y);
cout << cnt;
for (int i = 0; i <= xlen; i++) {
delete[] c[i];
delete[] b[i];
}
delete[] c;
delete[] b;
return 0;
}