题目链接:https://cn.vjudge.net/contest/269853#problem/B
题目描述:
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
题意:给定三个字符串,第三个的长度是前两个的和。问第一个和第二个字符串,不改变在相应字符串中相对位置的前提下,能否组成第三个字符串。
这里用dp[i][j]来表示第一个字符串中的前i个字符与第二个字符串中的前j个字符能否组成第三个字符串的前i+j个字符。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1010;
char a[210],b[210],c[410];
int dp[210][210];
int main()
{
int T;
while(scanf("%d",&T)!=EOF)
{
int cnt=1;
while(T--)
{
scanf("%s%s%s",a,b,c);
int lena=strlen(a);
int lenb=strlen(b);
memset(dp,0,sizeof(dp));
for(int i=0;i<=lena;i++)
{
if(a[i]==c[i])
dp[i][0]=1;
else
break;
}
for(int j=0;j<=lenb;j++)
{
if(b[j]==c[j])
dp[0][j]=1;
else
break;
}
for(int i=0;i<=lena;i++)
for(int j=0;j<=lenb;j++)
{
if(c[i+j-1]==a[i-1]&&dp[i-1][j]==1)
dp[i][j]=1;
if(c[i+j-1]==b[j-1]&&dp[i][j-1]==1)
dp[i][j]=1;
}
if(dp[lena][lenb])
printf("Data set %d: yes\n",cnt++);
else
printf("Data set %d: no\n",cnt++);
}
}
return 0;
}