ZOJ 1004 Anagrams by Stack dfs回溯

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4

回溯,说起来简单,做起题来要多加纠结有多纠结。。。

真是对搜索一窍不通,做的郁闷

 

题意:对第一个字符串操作 不断入栈出栈  有几种方法可以得到第二个字符串

题意纠结难懂,程序更是,看了别人的代码还是稀里糊涂的,搜索搜索,come on,please

代码: 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
int len1,len2;
bool s[202];
char s1[101],s2[101];
stack<char>S;

void dfs(int i,int j,int k)
{
    if(j>=len2)
    {
        for(int x=0;x<k;x++)
        if(s[x])printf("i ");
        else printf("o ");
        printf("\n");
        return;
    }

    if(i<len1)
    {
     
      S.push(s1[i]);
	   s[k]=1;
      dfs(i+1,j,k+1);
      S.pop();
    }
    if(!S.empty()&&s2[j]==S.top())
    {
        char ch=S.top();
        S.pop();
        s[k]=0;
        dfs(i,j+1,k+1);
        S.push(ch);
    }
}
int main()
{
    while(~scanf("%s%s",s1,s2))
    {
        len1=strlen(s1);
        len2=strlen(s2);
        while(!S.empty())S.pop();
        printf("[\n");
        dfs(0,0,0);
        printf("]\n");
    }
    return 0;
}

  

posted @ 2012-02-25 02:11  快乐.  阅读(175)  评论(0编辑  收藏  举报