blob: 8b124ed9e64f843ca7d13734f3907371617ee11b (
plain)
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
|
#include <iostream>
#include <string>
using std::string;
int edit_distance(const string &str1, const string &str2)
{
int s1 = str1.length() + 1;
int s2 = str2.length() + 1;
int *m = new int[s1 * s2];
for (int i = 0; i < s1; i++) m[i] = i;
for (int i = 0; i < s2; i++) m[i * s1] = i;
for (int i = 1; i < s2; i++) {
for (int j = 1; j < s1; j++) {
int insertion = m[i * s1 + j - 1] + 1;
int deletion = m[(i - 1 ) * s1 + j] + 1;
int match = m[(i - 1) * s1 + j - 1];
int mismatch = match + 1;
if (str2[i - 1] == str1[j - 1]) {
/* m[i, j] = ((insertion < deletion) ? */
m[i * s1 + j] = ((insertion < deletion) ?
((insertion < match) ? insertion : match)
: ((deletion < match) ? deletion : match));
}
else {
m[i * s1 + j] = ((insertion < deletion) ?
((insertion < mismatch) ? insertion : mismatch)
: ((deletion < mismatch) ? deletion : mismatch));
}
}
}
/* for (int i = 0; i < s2; i++) { */
/* for (int j = 0; j < s1; j++) */
/* std::cout << m[i * s1 + j] << " "; */
/* std::cout << std::endl; */
/* } */
delete [] m;
return m[s1 * s2 - 1];
}
int main() {
string str1;
string str2;
std::cin >> str1 >> str2;
std::cout << edit_distance(str1, str2) << std::endl;
return 0;
}
|