Problem Description
Given three strings, you are to determine whether the third string can be formed by combining the characters in the first two strings. The first two strings can be mixed arbitrarily, but each must stay in its original order.
For example, consider forming “tcraete” from “cat” and “tree”:
String A: cat
String B: tree
String C: tcraete
As you can see, we can form the third string by alternating characters from the two strings. As a second example, consider forming “catrtee” from “cat” and “tree”:
String A: cat
String B: tree
String C: catrtee
Finally, notice that it is impossible to form “cttaree” from “cat” and “tree”.
Input
The first line of input contains a single positive integer from 1 through 1000. It represents the number of data sets to follow. The processing for each data set is identical. The data sets appear on the following lines, one data set per line.
For each data set, the line of input consists of three strings, separated by a single space. All strings are composed of upper and lower case letters only. The length of the third string is always the sum of the lengths of the first two strings. The first two strings will have lengths between 1 and 200 characters, inclusive.
Output
For each data set, print:
Data set n: yes
if the third string can be formed from the first two, or
Data set n: no
if it cannot. Of course n should be replaced by the data set number. See the sample output below for an example.
Sample Input
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
Sample Output
Data set 1: yes
Data set 2: yes
Data set 3: no
题意:给三个串,问第三个串能不能由前两个串组成,并且单个字符串的顺序不变。
思路:简单记忆化搜索。
(刚开始想歪了,想先判断这俩串和第三个串的字母数量是不是一样,然后用两次最长公共子序列做,我觉得这么做可能会超时,但是没想到wa了,,到现在也不知道为什么,感觉这种思路也ok啊。。就是麻烦点)
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int f[210][210];
int la,lb,lc;
string s1,s2,s3;
int dfs(int i,int j,int k)
{
if(i>=la&&j>=lb)
{
if(k>=lc)
return 1;
return 0;
}
if(f[i][j]!=-1)
return f[i][j];
int ans=0;
if(s1[i]==s3[k]&&i<la)
ans=max(ans,dfs(i+1,j,k+1));
if(s2[j]==s3[k]&&j<lb)
ans=max(ans,dfs(i,j+1,k+1));
return f[i][j]=ans;
}
int main()
{
int t,cas=1;
cin>>t;
while(t--)
{
cin>>s1>>s2>>s3;
la=s1.size(),lb=s2.size(),lc=s3.size();
printf("Data set %d: ",cas++);
memset(f,-1,sizeof f);
if(dfs(0,0,0)<=0)
printf("no\n");
else
printf("yes\n");
}
return 0;
}