zoj 1642 Match for Bonus(动态规划)

本文探讨了一种解决字符匹配问题的方法,通过动态规划算法计算两个字符串之间的最大得分,每匹配一个公共字符即可增加分数。文章详细解释了算法思路、代码实现以及示例输入输出。
Match for Bonus

Time Limit: 2 Seconds      Memory Limit: 65536 KB

Roy played a game with his roommates the other day. 

His roommates wrote 2 strings of characters, and gave each character a bonus value. When Roy pinned the positions of one common character in the 2 strings, the bonus value of that character would be added to Roy's score. However at the mean time, the 2 characters and those before them in the strings would be erased.

Roy now needs your help, because he wants to know the maximum score he can get.


Input

There are several test cases. 

For each test case, the first line contains an integer N.

The following N lines describe a list of N characters and their bonus values.

Then the following 2 lines give the 2 strings.


Output

For each test case, output in one line the best score Roy can get.


Sample Input

3
a 1
b 1
c 1
abc
bca
3
a 1
b 10
c 100
abc
cab


Sample Output

2
100

 

度娘的思路:本题的算法思想与LCS问题类似。设输入的2个字符串s1[0...n]和s2[0...m],另f(i,j)表示子串s1[0...i]和s2[0...j]对应的最大得分,则有DP递推式
f(i,j)=max{f(i-1,j-1)+(x[i]==y[j])?v(x[i]):0,f(i,j-1),f(i-1,j)},(v(c)表示字符c的分值),所以最大得分便是f(n,m)。

我呢,各种犯错,记录下

View Code
 1 # include<stdio.h>
 2 # include<iostream>
 3 # include<string.h>
 4 # include<map>
 5 using namespace std;
 6 # define maxn 2005 //大小是2005,考点
 7 
 8 char ss[3];
 9 int x;
10 int d[maxn][maxn];
11 char s1[maxn],s2[maxn];
12 int max(int a,int b)
13 {
14     return a>b?a:b;
15 }
16 int i,j,n;
17 int main()
18 {
19     map<char,int>s;
20     while(scanf("%d",&n)!=EOF)
21     {
22         s.clear(); //map函数没有这个的话,会出现Segmentation Fault,是下标出错
23         for(i=0; i<n; i++)
24         {
25             scanf("%s%d",ss,&x);
26             s[ss[0]] = x;
27         }
28         scanf("%s%s",s1,s2);
29         memset(d,0,sizeof(d));
30         int ans=0; //用到ans,这里的结果最大的不一定是最后一个,奇怪
31         for(i=0; s1[i]; i++) //这里只能用s1[],不是用n,字符串的长度不一定是n
32         {
33             for(j=0; s2[j]; j++)  
34             {
35                 int temp = d[i][j];
36                 if(s1[i] == s2[j])  //这种方法,初始化了每个字符的值
37                     temp += s[s1[i]];
38                 d[i+1][j+1] = max(temp,max(d[i][j+1],d[i+1][j]));
39                 if(d[i+1][j+1]>ans) ans=d[i+1][j+1];
40             }
41         }
42         for(i=0;i<=n;i++)
43         {
44                 for(j=0;j<=n;j++)
45                 printf(" %d ",d[i][j]);
46                 puts("");
47         }
48         printf("%d\n",ans);
49     }
50     return 0;
51 }

 

 

转载于:https://www.cnblogs.com/acm-bingzi/archive/2013/04/04/3000019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值