Strings - UVa 11081 dp

本文介绍了一个编程问题,即如何计算由两个字符串的子序列构成第三个特定字符串的不同方式的数量,并提供了一段AC代码作为解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]);
  }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值