ZOJ 1004 DFS回溯法

咋一看此题有点不知所措,后来看了别人的题解,感悟良多用你自己的四轮现在草稿纸上

画画,边入栈边匹配,匹配则出栈,不匹配则入栈,如此下去。。。

View Code
 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<stack>
 6 #include<iostream>
 7 #include<string>
 8 
 9 using namespace std;
10 
11 int i,j,k,ans;
12 char *ps=NULL, *pe=NULL;
13 char str[1001],first[1001],last[1001];
14 stack<char>s;
15 
16 void DFS()
17 {
18    int  l;
19    if(*pe == '\0')
20    {
21        for(l=0; l!=ans; l++)          
22        {
23          cout<<str[l]<<" ";//此处要小心为此贡献了一次PE
24        }  
25        cout<<endl;  
26    }
27    
28    if(*ps != '\0')//刚开始和下面的的互换了导致最后的顺讯颠倒了
29    {
30       s.push(*ps);                 
31       str[ans++] = 'i';         
32       ++ps;
33       DFS(); 
34       s.pop();
35        --ps;    
36        --ans;
37    } 
38    
39    if( !s.empty() )
40    {
41       char c = s.top(); 
42       if(c == *pe)  
43       {
44          s.pop();
45          str[ans++] = 'o'; 
46          ++pe;   
47          DFS();  
48          s.push(c);  
49          --pe;   
50          --ans;
51      }    
52    }     
53     
54 }
55     
56 int main()
57 {
58     
59     while(cin>>first>>last)
60     {
61       ans = 0;
62       ps =  first;
63       pe = last;
64      cout<<'['<<endl;
65       
66       DFS();
67       
68       cout<<']'<<endl;
69     
70     }  
71     
72     return 0;
73 }
74 
75     
posted @ 2012-09-02 22:28  zhongya  阅读(934)  评论(0编辑  收藏  举报