Background
Simple DP
Description
There is a string X, which is an extended string of X after the header and tail of x and any number of spaces are inserted in the middle. For example, the string X is "abcbcd ", the strings "abcb_c _", "_ a_bcbcd _", and "abcb_c _" are all extended strings of X. Here "_" represents space characters.
If A1 is an extension string of string A, B1 is an extension string of string B, and A1 and B1 have the same length, then, we define the distance between the string A1 and B1 as the sum of the characters in the corresponding position, while the distance between the two non-space characters is the absolute value of their ASCII code difference, the distance between the space character and any other character is a known value K, and the distance between the space character and the space character is 0. In all the extension strings of string a and string B, there must be two extension strings A1 and B1, so that the distance between A1 and B1 reaches the minimum, we define this distance as the distance between strings A and B.
Please write a program to find the distance between string a and string B.
Format input format
The first line of the input file is string a and the second line is string B. A and B consist of lowercase letters and cannot exceed 2000 characters in length. The third behavior is an integer k (1 ≤ k ≤ 100), indicating the distance between spaces and other characters.
Output Format
Only one row of the output file contains an integer, indicating the distance between the obtained strings A and B.
Example 1 input 1 [copy]
cmcsnmn2
Sample output 1 [copy]
10
Restrictions
1 s
Prompt
It is dedicated to beginners of DP and increases noip2009 confidence for oier ~~
Question
This question is actually LCS, F [I] [J] = min {f [I-1] [J-1] + dist (A [I], B [J]), f [I-1] [J] + k, F [I] [J-1] + k}
Code
1 /*Author:WNJXYK*/ 2 #include<cstdio> 3 #include<iostream> 4 #include<cstring> 5 #include<string> 6 using namespace std; 7 string a,b; 8 int la,lb; 9 const int Maxn=2000;10 long long f[Maxn+5][Maxn+5];11 long long k;12 int remin(int a,int b){13 if (a<b) return a;14 return b;15 }16 int abs(int x){17 if (x<0) return -x;18 return x;19 }20 int main(){21 cin>>a>>b;22 cin>>k;23 la=a.length();lb=b.length();24 memset(f,127,sizeof(f));25 f[0][0]=0;26 for (int i=1;i<=la;i++) f[i][0]=f[i-1][0]+k;27 for (int i=1;i<=lb;i++) f[0][i]=f[0][i-1]+k;28 for (int i=1;i<=la;i++){29 for (int j=1;j<=lb;j++){30 f[i][j]=remin(f[i][j],f[i-1][j-1]+abs(a[i-1]-b[j-1]));31 f[i][j]=remin(f[i][j],f[i-1][j]+k);32 f[i][j]=remin(f[i][j],f[i][j-1]+k);33 }34 }35 cout<<f[la][lb]<<endl;36 return 0;37 }
View code
Vijos p1680 distance