#2535. 2023 CSP-J1 真题 · 完善程序(编辑距离)

2023 CSP-J1 真题 · 完善程序(编辑距离)

2023 CSP-J1 真题(120 分钟,总分 100 分)

完善程序(编辑距离)(共 5 题,共 15.0 分)

1. (编辑距离)给定两个字符串,每次操作可以选择删除(Delete)、插入(Insert)、替换(Replace)一个字符,求将第一个字符串转换为第二个字符串所需要的最少操作次数。

试补全动态规划算法。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int min(int x, int y, int z) {
    return min(min(x, y), z);
}

int edit_dist_dp(string str1, string str2) {
    int m = str1.length();
    int n = str2.length();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));

    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0)
                dp[i][j] = ①;
            else if (j == 0)
                dp[i][j] = ②;
            else if (③)
                dp[i][j] = ④;
            else

                dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], ⑤);
        }
    }
    return dp[m][n];
}

int main() {
    string str1, str2;
    cin >> str1 >> str2;
    cout << "Minimum number of operations: "
         << edit_dist_dp(str1, str2) << endl;
    return 0;
}

①处应填()

{{ select(1) }}

  • cpp j
  • cpp i
  • cpp m
  • cpp n

2. ②处应填()

{{ select(2) }}

  • cpp j
  • cpp i
  • cpp m
  • cpp n

3. ③处应填()

{{ select(3) }}

  • cpp str1[i-1]==str2[j-1]
  • cpp str1[i]==str2[j]
  • cpp str1[i-1]!=str2[j-1]
  • cpp str1[i]!=str2[j]

4. ④处应填()

{{ select(4) }}

  • cpp dp[i-1][j-1]+1
  • cpp dp[i-1][j-1]
  • cpp dp[i-1][j]
  • cpp dp[i][j-1]

5. ⑤处应填()

{{ select(5) }}

  • cpp dp[i][j]+1
  • cpp dp[i-1][j-1]+1
  • cpp dp[i-1][j-1]
  • cpp dp[i][j]