acwing 899 Edit distance (linear DP)

Topic

Insert picture description here

answer

  1. For the application of the shortest edit distance, we only need to traverse each string to find whether the shortest distance between each string and the input string is less than or equal to the limit, and if it meets the answer, +1
  1. Insert picture description here

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1100;

int n, m;
char str[N][N];
int f[N][N];

int editor(char a[], char b[]) {
    
    

    int la = strlen(a + 1), lb = strlen(b + 1);

    for (int i = 0; i <= lb; i++) f[0][i] = i;
    for (int i = 0; i <= la; i++) f[i][0] = i;

    for (int i = 1; i <= la; i++) {
    
    
        for (int j = 1; j <= lb; j++) {
    
    
            f[i][j] = min(f[i - 1][j] + 1, f[i][j - 1] + 1);
            if (a[i] == b[j]) f[i][j] = min(f[i][j], f[i - 1][j - 1]);
            else f[i][j] = min(f[i][j], f[i - 1][j - 1] + 1);
        }
    }

    return f[la][lb];
}

int main() {
    
    

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> str[i] + 1;

    while (m--) {
    
    
        char s[N];
        int limit;
        cin >> s + 1 >> limit;
        int res = 0;
        for (int i = 1; i <= n; i++) {
    
    
            if (editor(s, str[i]) <= limit) {
    
    
                res++;
            }
        }
        cout << res << endl;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114850796