#include <stdio.h> #include <string.h> #define INF -1 #define MAX 1010 int map[MAX][MAX]; char a[MAX], b[MAX]; int min(int a, int b, int c) { return a<b?(a<c?a:c):(b<c?b:c); //不要一不小心写成 > } int dif(int i, int j) { if( a[i-1] == b[j-1]) //注意图的第0行 or 第0列表示什么 算法概论P180图6-4 return 0; else return 1; } int dp(int i, int j) { if( map[i][j] != INF) return map[i][j]; if(i == 0) return map[i][j] = j; if(j == 0) return map[i][j] = i; else { return map[i][j] = min( dp(i,j-1) + 1, dp(i-1,j) + 1, dp(i-1,j-1) + dif(i, j)); } } int main() { int N, i, j; //freopen("3.txt", "r", stdin); scanf("%d", &N); while(N--) { scanf("%s", &a); scanf("%s", &b); memset(map, INF, sizeof(map)); i = strlen(a); j = strlen(b); printf("%d ", dp(i, j)); } return 0; }
HRBUST 1284