【动态规划】Vijos P1680 距离

题目链接:

  https://vijos.org/p/1680

题目大意:

  设有字符串X,我们称在X的头尾及中间插入任意多个空格后构成的新字符串为X的扩展串,如字符串X为”abcbcd”,则字符串“abcb_c_”,“_a_bcbcd_”和“abcb_c_”都是X的扩展串,这里“_”代表空格字符。如果A1是字符串A的扩展串,B1是字符串B的扩展串,A1与B1具有相同的长度,那么我扪定义字符串A1与B1的距离为相应位置上的字符的距离总和,而两个非空格字符的距离定义为它们的ASCII码的差的绝对值,而空格字符与其他任意字符之间的距离为已知的定值K,空格字符与空格字符的距离为0。在字符串A、B的所有扩展串中,必定存在两个等长的扩展串A1、B1,使得A1与B1之间的距离达到最小,我们将这一距离定义为字符串A、B的距离。求字符串A、B的距离。

题目思路:

  【动态规划】

  f[i][j]表示A匹配到i,B匹配到j的最优值。

  初始化f[0][i]=f[i][0]=i*K;

 

 1 //
 2 //by coolxxx
 3 ////<bits/stdc++.h>
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<string>
 7 #include<iomanip>
 8 #include<map>
 9 #include<memory.h>
10 #include<time.h>
11 #include<stdio.h>
12 #include<stdlib.h>
13 #include<string.h>
14 //#include<stdbool.h>
15 #include<math.h>
16 #define min(a,b) ((a)<(b)?(a):(b))
17 #define max(a,b) ((a)>(b)?(a):(b))
18 #define abs(a) ((a)>0?(a):(-(a)))
19 #define lowbit(a) (a&(-a))
20 #define sqr(a) ((a)*(a))
21 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
22 #define mem(a,b) memset(a,b,sizeof(a))
23 #define eps (1e-8)
24 #define J 10
25 #define MAX 0x7f7f7f7f
26 #define PI 3.14159265358979323
27 #define N 2004
28 using namespace std;
29 typedef long long LL;
30 int cas,cass;
31 int n,m,lll,ans;
32 char s1[N],s2[N];
33 int f[N][N];
34 int main()
35 {
36     #ifndef ONLINE_JUDGE
37 //    freopen("1.txt","r",stdin);
38 //    freopen("2.txt","w",stdout);
39     #endif
40     int i,j;
41 //    for(scanf("%d",&cas);cas;cas--)
42 //    for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
43     while(~scanf("%s%s",s1,s2))
44 //    while(~scanf("%d",&n))
45     {
46         //mem(f,0x7f);
47         scanf("%d",&cas);
48         n=strlen(s1);m=strlen(s2);
49         for(i=1;i<=m;i++)f[0][i]=i*cas;
50         for(i=1;i<=n;i++)f[i][0]=i*cas;
51         for(i=1;i<=n;i++)
52         {
53             for(j=1;j<=m;j++)
54             {
55                 f[i][j]=min(f[i-1][j],f[i][j-1])+cas;
56                 f[i][j]=min(f[i][j],f[i-1][j-1]+abs(s1[i-1]-s2[j-1]));
57             }
58         }
59         printf("%d\n",f[n][m]);
60     }
61     return 0;
62 }
63 /*
64 //
65 
66 //
67 */
View Code

 

posted @ 2016-08-16 11:13  Cool639zhu  阅读(347)  评论(0编辑  收藏  举报