P1279 字串距离
P1279 字串距离
一看就是字符串dp,然而并不会,骗分之后爆零了。以后dp题要好好想想转移方程。f[i][j]表示是a串选了前i个字符,b串选了前j个字符的距离。显然(QAQ)
f[i][j]=min(min(f[i-1][j]+k,f[i][j-1]+k),f[i-1][j-1]+abs(a[i]-b[j]));
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<algorithm> 5 #include<cmath> 6 #include<ctime> 7 #include<queue> 8 #include<map> 9 #include<set> 10 #include<cstring> 11 #define inf 2147483647 12 #define For(i,a,b) for(register int i=a;i<=b;i++) 13 #define p(a) putchar(a) 14 #define g() getchar() 15 //by war 16 //2017.10.25 17 using namespace std; 18 char a[2010],b[2010]; 19 int l1,l2; 20 int f[2010][2010]; 21 int k; 22 23 void in(int &x) 24 { 25 int y=1; 26 char c=g();x=0; 27 while(c<'0'||c>'9') 28 { 29 if(c=='-') 30 y=-1; 31 c=g(); 32 } 33 while(c<='9'&&c>='0')x=x*10+c-'0',c=g(); 34 x*=y; 35 } 36 void o(int x) 37 { 38 if(x<0) 39 { 40 p('-'); 41 x=-x; 42 } 43 if(x>9)o(x/10); 44 p(x%10+'0'); 45 } 46 int main() 47 { 48 cin>>(a+1)>>(b+1); 49 l1=strlen(a+1); 50 l2=strlen(b+1); 51 in(k); 52 For(i,1,l1) 53 f[i][0]=k*i; 54 For(i,1,l2) 55 f[0][i]=k*i; 56 For(i,1,l1) 57 For(j,1,l2) 58 f[i][j]=min(min(f[i-1][j]+k,f[i][j-1]+k),f[i-1][j-1]+abs(a[i]-b[j])); 59 o(f[l1][l2]); 60 return 0; 61 }