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".
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.
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.
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
Data set 1: yes
Data set 2: yes
Data set 3: no
按顺序合并串,类似于找最长公共子序列,用n^2dp就可以了
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define per(i,j,k) for (int i=j;i>=k;i--)
#define inone(x) scanf("%d",&x)
#define intwo(x,y) scanf("%d%d",&x,&y)
typedef pair<int,int> pii;
const int N=1e3+10;
const int mod=1e9+7;
int T,dp[N][N];
char a[N],b[N],c[N];
int main()
{
int cas=1;
for(inone(T);T--;cas++)
{
scanf("%s%s%s",a+1,b+1,c+1);
int la=strlen(a+1),lb=strlen(b+1),lc=strlen(c+1);
if (la+lb!=lc) printf("Data set %d: no\n",cas);
else
{
dp[0][0]=1;
for (int i=1;i<=la;i++) dp[i][0]=dp[i-1][0]&&a[i]==c[i];
for (int i=1;i<=lb;i++) dp[0][i]=dp[0][i-1]&&b[i]==c[i];
for (int i=1;i<=la;i++)
{
for (int j=1;j<=lb;j++)
{
dp[i][j]=(dp[i][j-1]&&b[j]==c[i+j])||(dp[i-1][j]&&a[i]==c[i+j]);
}
}
printf("Data set %d: %s\n",cas,dp[la][lb]?"yes":"no");
}
}
return 0;
}