zoj 1004 深度优先遍历

来源:互联网 发布:程序员怎么去找视频 编辑:程序博客网 时间:2024/05/19 13:59

题目大意:两组数,第一组字符串通过压栈弹栈顺序,得到第二组数据,输出压栈弹栈顺序,解有多个,按照字典序输出

解题思路:深度优先遍历,借助一个栈来保存第一个字符串压栈的状态,优先考虑压栈操作,注意的是边界条件,满足第二个字符串扫描到尾部时,输出结果

#include <iostream>#include <cstdio>#include <cstring>#include <stack>using namespace std;const int maxn = 101;char str1[maxn], str2[maxn];char result[2 * maxn];int len1, len2;void dfs(stack<char> &st, int pos1, int pos2, int depth);int main(){       while(scanf("%s %s", str1, str2) != EOF)    {        stack<char> st;        len1 = strlen(str1);        len2 = strlen(str2);        if(len1 != len2)        {            printf("[\n]\n");            continue;        }        printf("[\n");        dfs(st, 0, 0, 0);        printf("]\n");    }       return 0;}void dfs(stack<char> &st, int pos1, int pos2, int depth){    if(pos2 >= len2)    {        for(int i = 0; i < depth; i++)            printf("%c ", result[i]);        printf("\n");        return;    }    if(pos1 < len1)    {        result[depth] = 'i';        st.push(str1[pos1]);        dfs(st, pos1 + 1, pos2, depth + 1);        st.pop();    }    if(!st.empty() && st.top() == str2[pos2])    {        result[depth] = 'o';        st.pop();        dfs(st, pos1, pos2 + 1, depth + 1);        st.push(str2[pos2]);    }}


 

原创粉丝点击