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
3cat tree tcraetecat tree catrteecat tree cttaree
Sample Output
Data set 1: yesData set 2: yesData 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;}}