程序设计与算法(二)Zipper

题目
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

官方代码

//By Guo Wei
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
char a[300], b[300], c[700];
int La, Lb, Lc;
char valid[210][210][410];
bool Valid(int as, int bs, int cs)
{
	if (cs == Lc) {
		if (as == La && bs == Lb)
			return true;
		else
			return false;
	}
	if (valid[as][bs][cs] != -1)
		return valid[as][bs][cs];
	bool b1 = false, b2 = false;
	if (a[as] == c[cs])
		b1 = Valid(as + 1, bs, cs + 1);
	if (b[bs] == c[cs])
		b2 = Valid(as, bs + 1, cs + 1);
	valid[as][bs][cs] = b1 || b2;
	return b1 || b2;

}
int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; ++i) {
		scanf("%s%s%s", a, b, c);
		La = strlen(a);
		Lb = strlen(b);
		Lc = strlen(c);
		//memset(valid,0xff,sizeof(valid));  //不能用这个,用这个就是 n^3的了 
		for (int cs = 0; cs <= Lc; ++cs)
			for (int as = 0; as <= La; ++as) {
				int bs = cs - as; //因为bs必须是 cs-as才有意义,所以不用让bs从0走到Lb,要是那样就搞成n^3的了 
				valid[as][bs][cs] = -1;
			}
		if (Valid(0, 0, 0))
			printf("Data set %d: yes\n", i + 1);
		else
			printf("Data set %d: no\n", i + 1);
	}
	return 0;
}
发布了26 篇原创文章 · 获赞 11 · 访问量 2301

猜你喜欢

转载自blog.csdn.net/qq_41731507/article/details/102308965
今日推荐