[sicily online]1010. Zipper

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

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

题目分析:

用递归或者遍历来查找,会有重叠子问题。所以可以采用dp来做,设x[i][j]表示从第一个串中取第i个,第二个串中取j个,且是bool类型

那么递归式就是x[i][j]=true if(x[i-1][j]==true&&x1[i-1]=x3[i-1+j]||x[i][j-1]==true&&x2[j-1]==x3[j-1+i])

用两个for循环求x数组

#include<iostream>
#include <iomanip>
#include<stdio.h>
#include<cmath>
#include<iomanip>
#include<list>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <stack>
#include<queue>
#include<string.h>
using namespace std;

int main()
{
	int n;
	scanf("%d",&n);
	for(int xx=0;xx<n;xx++)
	{
		string x1,x2,x3;
		cin>>x1>>x2>>x3;

		bool data[201][201];
		int i=0;
		for(i=1;i<=x1.size();i++)
		{
			if(x1[i-1]==x3[i-1])
				data[i][0]=true;
			else break;
		}
		for(;i<=x1.size();i++)
			data[i][0]=false;
		for(i=1;i<=x2.size();i++)
		{
			if(x2[i-1]==x3[i-1])
				data[0][i]=true;
			else break;
		}
		for(;i<=x2.size();i++)
			data[0][i]=false;
		for(i=1;i<=x1.size();i++)
		{
			for(int j=1;j<=x2.size();j++)
			{
				if(data[i-1][j]==true&&x1[i-1]==x3[i-1+j]||data[i][j-1]==true&&x2[j-1]==x3[j-1+i])
					data[i][j]=true;
				else data[i][j]=false;
			}//
		}
		cout<<"Data set "<<xx+1<<": ";
		if(data[x1.size()][x2.size()])
			cout<<"yes"<<endl;
		else cout<<"no"<<endl;
	}
}


你可能感兴趣的:([sicily online]1010. Zipper)