poj 3267 dp
f[i]=min(f[i],num-strlen(word)+f[i+num])
注意数组范围
match非常巧妙的运用了j与i的匹配
dp两层循环加一个函数(计算距离)
#include <stdio.h> #include <string.h> #define maxn 605 #define maxl 305 int n,m; char str[maxl],map[maxn][maxl]; int f[maxl]; int min(int k,int t) { return k>t?t:k; } int match(char *st1, char *st2) { if (st1[0] != st2[0]) return 0; int len = strlen(st2); int j = 0; for (int i = 0; i < len; i++) { while (st1[j] != '\0' && st1[j] != st2[i]) j++; if (st1[j] == '\0') return 0; j++; } return j; } int main() { int i,j,num; scanf("%d%d",&n,&m); scanf("%s",str); for(i=0;i<n;i++) scanf("%s",map[i]); f[m]=0; for(i=m-1;i>=0;i--) { f[i]=f[i+1]+1; for(j=0;j<n;j++) { if(num=match(&str[i],map[j])) f[i]=min(f[i],int(num-strlen(map[j])+f[i+num])); } } printf("%d\n",f[0]); return 0; }