深搜———ZOJ 1004:anagrams by stack

细节问题各种虐!!

其实就是简单的一个深搜

看成二叉树来理解:每个节点有两个枝:入栈和出栈。

剪枝操作:只有当栈顶元素和当前位置的目标字符相同时才出栈,否则就不出栈

dfs写三个参数:depth搜索深度,npush压栈数,npop出栈数

npush用于记录压栈数:主要判断当前压栈是否合理,以及要压入的元素在原串种的位置

npop用于记录出栈数:判断生成的目标串元素的位置

当npush==npop==目标串时,说明生成了一个可执行的操作串

注意输出操作串的时候一定要用depth参数来控制,因为在多次输入时string 的最大长度已经改变,只有利用depth才能确定该字符串的那一部分是当前所生成的。

贴代码!

# include<iostream>
# include<string>
# include<cstdio>
# include<cstring>
using namespace std;

string source;
string target;

char solution[200];
char s[200];

int top;

void dfs(int depth, int npush, int npop)
{
    if (npush == target.length() && npop == target.length())
    {
        for (int i = 0; i < depth; i++)
        {
                cout << solution[i]<<" ";
        }
        cout << endl;
        return;
    }

    if (npush < target.length())
    {
        s[top++] = source[npush];
        solution[depth] = 'i';
        dfs(depth + 1, npush + 1, npop);
        top--;
    }

    if (top > 0 && s[top - 1] == target[npop])
    {
        solution[depth] = 'o';
        char temp = s[top - 1];
        top--;
        dfs(depth + 1, npush, npop + 1);
        s[top++] = temp;
    }

    return;

}

int main()
{
    while (cin>>source>>target)
    {
        top = 1;
        cout << "[" << endl;
        if (source.length() == target.length())
            dfs(0,0,0);
        cout << "]" << endl;
    }

    return 0;
}

 

posted @ 2015-12-10 23:04  DigitalHermit  阅读(694)  评论(1编辑  收藏  举报