您的位置:首页 > 其它

zoj 1642 Match for Bonus(动态规划)

2013-04-04 22:45 363 查看
Match for BonusTime 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

# include<stdio.h>
# include<iostream>
# include<string.h>
# include<map>
using namespace std;
# define maxn 2005 //大小是2005,考点

char ss[3];
int x;
int d[maxn][maxn];
char s1[maxn],s2[maxn];
int max(int a,int b)
{
return a>b?a:b;
}
int i,j,n;
int main()
{
map<char,int>s;
while(scanf("%d",&n)!=EOF)
{
s.clear(); //map函数没有这个的话,会出现Segmentation Fault,是下标出错
for(i=0; i<n; i++)
{
scanf("%s%d",ss,&x);
s[ss[0]] = x;
}
scanf("%s%s",s1,s2);
memset(d,0,sizeof(d));
int ans=0; //用到ans,这里的结果最大的不一定是最后一个,奇怪
for(i=0; s1[i]; i++) //这里只能用s1[],不是用n,字符串的长度不一定是n
{
for(j=0; s2[j]; j++)
{
int temp = d[i][j];
if(s1[i] == s2[j])  //这种方法,初始化了每个字符的值
temp += s[s1[i]];
d[i+1][j+1] = max(temp,max(d[i][j+1],d[i+1][j]));
if(d[i+1][j+1]>ans) ans=d[i+1][j+1];
}
}
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
printf(" %d ",d[i][j]);
puts("");
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: