forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path6.cpp
47 lines (38 loc) Β· 1.31 KB
/
6.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
#include <bits/stdc++.h>
using namespace std;
// λ λ¬Έμμ΄μ μ
λ ₯ λ°κΈ°
string str1;
string str2;
// μ΅μ νΈμ§ 거리(Edit Distance) κ³μ°μ μν λ€μ΄λλ―Ή νλ‘κ·Έλλ°
int editDist(string str1, string str2) {
int n = str1.size();
int m = str2.size();
// λ€μ΄λλ―Ή νλ‘κ·Έλλ°μ μν 2μ°¨μ DP ν
μ΄λΈ μ΄κΈ°ν
vector<vector<int> > dp(n + 1, vector<int>(m + 1));
// DP ν
μ΄λΈ μ΄κΈ° μ€μ
for (int i = 1; i <= n; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= m; j++) {
dp[0][j] = j;
}
// μ΅μ νΈμ§ 거리 κ³μ°
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// λ¬Έμκ° κ°λ€λ©΄, μΌμͺ½ μμ ν΄λΉνλ μλ₯Ό κ·Έλλ‘ λμ
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
// λ¬Έμκ° λ€λ₯΄λ€λ©΄, μΈ κ°μ§ κ²½μ° μ€μμ μ΅μκ° μ°ΎκΈ°
else { // μ½μ
(μΌμͺ½), μμ (μμͺ½), κ΅μ²΄(μΌμͺ½ μ) μ€μμ μ΅μ λΉμ©μ μ°Ύμ λμ
dp[i][j] = 1 + min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1]));
}
}
}
return dp[n][m];
}
int main(void) {
cin >> str1 >> str2;
// μ΅μ νΈμ§ 거리 μΆλ ₯
cout << editDist(str1, str2) << '\n';
}