【poj_2192】
【vj链接】
这道题告诉我们如果是分解子问题的dp,即使一开始找不到子问题,想一想dfs,说不定dfs里的参数就是子问题……
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.
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
Data set 1: yes
Data set 2: yes
Data set 3: no
第一行输入一个n
接下来n行,每行输入三个字符串
如果前两个字符串能组合成第三个,输出yes,不然输出no
这里组合的意思是两个字符串可以交叉,但相对于在原字符串里的顺序不能变
一开始没有看出子问题,用dfs直接就TLE了,然后加了dp[i][j][k]又MLE了……
因为k始终等于i+j……
这里的dp[i][j]我也不清楚代表什么,反正之前dfs里用了那就肯定是个子问题
#include
#include
#include
#include
#include
#include
#define LL long long
using namespace std;
const int maxn = 201;
int n1,n2,n3;
char a[207],b[207],c[407];
int dp[maxn][maxn];
bool dfs(int i,int j,int k)
{
//printf("(%d,%d,%d) ",i,j,k);
if (dp[i][j] != -1) return dp[i][j];
if(i//printf("A");
if(k==n3-1)
{
if (dp[i][j] == -1) dp[i][j] = 1;
return true;
}
if(dfs(i+1,j,k+1))
{
if (dp[i][j] == -1) dp[i][j] = 1;
return true;
}
}
if(j//printf("B");
if(k==n3-1)
{
if (dp[i][j] == -1) dp[i][j] = 1;
return true;
}
if(dfs(i,j+1,k+1))
{
if (dp[i][j] == -1) dp[i][j] = 1;
return true;
}
}
if (dp[i][j] == -1) dp[i][j] = 0;
return false;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out2.txt","w",stdout);
int n,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
memset(dp,-1,sizeof(dp));
printf("Data set %d: ",i);
scanf("%s%s%s",a,b,c);
n1=strlen(a);
n2=strlen(b);
n3=strlen(c);
if(dfs(0,0,0))
printf("yes\n");
else
printf("no\n");
}
return 0;
}