-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCS.cpp
90 lines (80 loc) · 1.65 KB
/
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
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
#include <iostream>
using namespace std;
const int m = 8;
const int n = 7;
//返回值结构
struct twoArrayPair
{
char b[m][n];
int c[m][n];
};
/*************************************************************/
/*
c[m][n]:保存了X和Y的LCS长度
b[m][n]: 帮助构造最优解
0 若i = 0 或 j = 0;
c[i][j] = c[i-1][j-1]+1 若i, j > 0 且xi = yi;
max(c[i][j-1], c[i-1][j]) 若i,j > 0 且 xi != yi;
*/
/*************************************************************/
twoArrayPair *LCSLength(char *x, char *y)
{
twoArrayPair *twoArray = new twoArrayPair;
//c, b数组初始化
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
(twoArray->b)[i][j] = ' ';
(twoArray->c)[i][j] = 0;
}
}
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
{
if (x[i] == y[j])
{
(twoArray->c)[i][j] = (twoArray->c)[i-1][j-1]+1;
(twoArray->b)[i][j] = '\\';
}
else if ((twoArray->c)[i-1][j] >= (twoArray->c)[i][j-1])
{
(twoArray->c)[i][j] = (twoArray->c)[i-1][j];
(twoArray->b)[i][j] = '|';
}
else
{
(twoArray->c)[i][j] = (twoArray->c)[i][j-1];
(twoArray->b)[i][j] = '-';
}
}
}
return twoArray;
}
//打印LCS
void printLCS(char (*b)[n], char *x, int i, int j)
{
if (i == 0 | j == 0)
return;
if (b[i][j] == '\\')
{
printLCS(b, x, i-1, j-1);
cout << x[i];
}
else if (b[i][j] == '|')
printLCS(b, x, i-1, j);
else
printLCS(b, x, i, j-1);
}
int main()
{
char x[] = "0ABCBDAB";
char y[] = "0BDCABA";
twoArrayPair *tt = LCSLength(x, y);
cout << "x与y的最长公共子序列是:" << endl;
printLCS(tt->b, x, m-1, n-1);
cout << endl;
system("pause");
return 0;
}