您的位置:首页 > 其它

POJ 2192 && HDU 1501 Zipper (记忆化搜索)

2015-07-07 14:47 609 查看
Zipper
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 16803Accepted: 5994
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

Source
Pacific Northwest 2004

题目链接:http://poj.org/problem?id=2192

题目大意:用两个字符串组成第三个字符串,要求两个字符串本身的相对位置不变,问能否组成

题目分析:一开始的想法是在串3中分先找串1判串2和先找串2判串1,结果wa了,提供一组别人给的数据:abca acba abacbaca

下面考虑搜索,直接搜的话倒着搜过了,正着搜超时,应该和数据有关,但是加上记忆化就怎么都不会超时了,dp[i][j]表示到第一个字符串的第i个位置和第二个字符串的第j个位置的状态有没有出现过,出现过就不用再搜了

代码:

#include <cstdio>
#include <cstring>
int const MAX = 1005;
char s1[MAX], s2[MAX], s3[MAX];
bool dp[MAX][MAX];
bool flag;

void DFS(int i1, int i2, int i3)
{
    if(flag || i3 == (int)strlen(s3))
    {
        flag = true;
        return;
    }
    if(dp[i1][i2])
        return;
    dp[i1][i2] = true;
    if(s1[i1] == s3[i3])
        DFS(i1 + 1, i2, i3 + 1);
    if(s2[i2] == s3[i3])
        DFS(i1, i2 + 1, i3 + 1);
    return;
}

int main()
{
    int T, ca = 1;
    scanf("%d", &T);
    while(T--)
    {
        memset(dp, false, sizeof(dp));
        flag = false;
        scanf("%s %s %s", s1, s2, s3);
        DFS(0, 0, 0);
        if(flag)
            printf("Data set %d: yes\n", ca ++);
        else
            printf("Data set %d: no\n", ca ++);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: