899. 编辑距离 - AcWing题库
题目描述:
思路:
可以看成是最短编辑距离的一个应用,
代码:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int N = 15,M=1010;
char str[M][N];
int n;
int m;
int edit_distance(char A[], char B[])
{
int f[N][N];
int a = strlen(A + 1), b = strlen(B + 1);
for (int i = 0; i <= a; i++) {
f[i][0] = i;
}
for (int i = 0; i <= b; i++)
{
f[0][i] = i;
}
for (int i = 1; i <= a; i++)
{
for (int j = 1; j <= b; 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[a][b];
}
int main()
{
scanf("%d%d", &n,&m);
for(int i=1;i<=n;i++)
{
scanf("%s", str[i] + 1);
}
for (int i = 1; i <= m; i++)
{
int res = 0;
char qu[N];
int t;
scanf("%s%d", qu + 1, &t);
for (int i = 1; i <= n; i++)
{
if (edit_distance(str[i], qu) <= t) res++;
}
printf("%d\n", res);
}
return 0;
}