BestCoder Round #47 1003

solution : 就按题解敲了一遍,好久没写这种dp

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <string>
 4 #include <vector>
 5 #include <algorithm>
 6 #include <iostream>
 7 using namespace std;
 8 typedef long long LL;
 9 const int MAX = 1e3+10;
10 const int MOD = 1e9+7;
11 int dp[MAX][MAX];
12 LL f[MAX][MAX];
13 int Next[30];
14 char a[MAX],b[MAX];
15 int main() {
16     int cas;
17     scanf("%d",&cas);
18     while(cas--) {
19         scanf("%s %s",a+1,b+1);
20         memset(dp,0,sizeof(dp));
21         int n=strlen(a+1);
22         int m=strlen(b+1);
23         for(int i=1;i<=n;i++) {
24             for(int j=1;j<=m;j++) {
25                 if(a[i]==b[j]) {
26                     dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1);
27                 }
28                 else {
29                     dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
30                 }
31             }
32         }
33         memset(f,0,sizeof(f));
34         for(int i=0;i<=n;i++) {
35             memset(Next,0,sizeof(Next));
36             for(int j=0;j<=m;j++) {
37                 if(dp[i][j]==0) {
38                     f[i][j]=1;
39                 }
40                 else {
41                     Next[b[j]-'a']=j;
42                     if(dp[i-1][j]==dp[i][j]) {
43                         f[i][j]=(f[i][j]+f[i-1][j])%MOD;
44                     }
45                     if(Next[a[i]-'a']) {
46                         int p=Next[a[i]-'a'];
47                         if(p&&dp[i-1][p-1]+1==dp[i][j]) {
48                             f[i][j]=(f[i][j]+f[i-1][p-1])%MOD;
49                         }
50                     }
51                 }
52             }
53         }
54         cout<<f[n][m]<<endl;
55     }

56 } 

posted @ 2015-07-12 11:46  acvc  阅读(208)  评论(0编辑  收藏  举报