您的位置:首页 > 其它

Strings - UVa 11081 dp

2014-08-06 22:45 405 查看
Problem H

Strings

Input:
Standard Input
Output: Standard Output


Given 3 strings of only lowercase letter you have to count the number of ways you can construct the third string by combining two subsequences from the first two strings.



After deleting 0 or more characters from a string we can get its subsequence. For example “a”, “b”, “c”, “ab”, “ac”, “bc” and “abc” all the strings are the subsequences of “abc”. A subsequence may also be empty.



Now suppose there are two subsequences “abc” and “de”. By combining them you can get the following strings “abcde”, “abdce”, “abdec”, “adbce”, “adbec”, “adebc”, “dabce”, “dabec”, “daebc” and “deabc”.



Input

The first line of the input contains a single integer T (0<T<271) indicating the number of test cases. Each test case contains 3 strings containing only lowercase characters. The lengths of the strings are between 1 and 60.



Output

For each test case output a single integer denoting the number of ways you can construct the third string from the first two string by the above way. The result may be very large. You should output the result%10007.

Sample Input Output for Sample Input

2

abc abc abc

abbcd bccde abcde


8

18

题意:由前两个字符串的子串组成第三个字符串,问有多少种方法。

思路:f1[i][j][k]表示第k个是从第一个字符串取的方法,f2[i][j][k]表示第k个是从第二个字符串取的方法,f表示f1和f2对应的和,然后递推。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s1[110],s2[110],s3[110];
int f1[110][110][110],f2[110][110][110],f[110][110][110];
int main()
{ int t,i,j,k,len1,len2,len3;
  scanf("%d",&t);
  while(t--)
  { scanf("%s%s%s",s1+1,s2+1,s3+1);
    len1=strlen(s1+1);
    len2=strlen(s2+1);
    len3=strlen(s3+1);
    memset(f1,0,sizeof(f1));
    memset(f2,0,sizeof(f2));
    memset(f,0,sizeof(f));
    for(i=0;i<=len1;i++)
     for(j=0;j<=len2;j++)
     { f1[i][j][0]=1;
       f2[i][j][0]=1;
       f[i][j][0]=1;
     }
    for(k=1;k<=len3;k++)
     for(i=0;i<=len1;i++)
      for(j=0;j<=len2;j++)
      { if(i==0 && j==0)
         continue;
        if(i>0)
        { f1[i][j][k]=f1[i-1][j][k];
          if(s1[i]==s3[k])
           f1[i][j][k]+=f[i-1][j][k-1];
        }
        if(j>0)
        { f2[i][j][k]=f2[i][j-1][k];
          if(s2[j]==s3[k])
           f2[i][j][k]+=f[i][j-1][k-1];
        }
        f[i][j][k]=(f1[i][j][k]+f2[i][j][k])%10007;
      }
    printf("%d\n",f[len1][len2][len3]);
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: