DP水题。最长公共子序列,稍稍变形即可。模型完全一样。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 #define MAX 2012 5 int dp[MAX][MAX],v[200]; 6 char a[MAX],b[MAX]; 7 int main() 8 { 9 int n,i,j; 10 while(cin>>n) 11 { 12 char ch; 13 int value; 14 memset(v,0,sizeof(0)); 15 memset(dp,0,sizeof(0)); 16 for(i = 1;i <= n;i++) 17 { 18 cin>>ch; 19 cin>>value; 20 v[ch] = value; 21 } 22 cin>>a>>b; 23 int lena = strlen(a); 24 int lenb = strlen(b); 25 int len = max(lena,lenb); 26 int ans = 0; 27 for(i = 1;i <= len;i++) 28 for(j = 1;j <= len;j++) 29 { 30 dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]); 31 if(a[i - 1] == b[j - 1]) 32 dp[i][j] = max(dp[i][j],dp[i - 1][j - 1] + v[a[i - 1]]); 33 if(dp[i][j] > ans) 34 ans = dp[i][j]; 35 } 36 cout<<ans<<endl; 37 } 38 return 0; 39 }