forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path6.cpp
More file actions
47 lines (38 loc) ยท 1.31 KB
/
6.cpp
File metadata and controls
47 lines (38 loc) ยท 1.31 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
#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';
}