hdu 1515 Anagrams by Stack

题目大意:

给你两个字符串,问:第一个字符串按入栈出栈规则,能否达到第二个字符串,输出所有的方法,i表示入栈,o表示出栈。

解题思路:DFS(深度优先搜索)

注意事项:

1、要注意回溯

2、要理清思路

 

View Code
 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <memory.h>
 4 
 5 using namespace std;
 6 char op[110];
 7 char ch1[110],ch2[110];
 8 char st1[110];
 9 int len,k;
10 
11 void dfs(int top1,int top2,int n){
12      char t;
13      if(top2 == len){
14              for(int i=0;i<k;i++){
15                      printf("%c ",op[i]);
16              }
17              printf("\n");
18              return;
19      }
20      if(n<len){
21      t = st1[top1+1];
22      st1[top1+1] = ch1[n];
23      op[k++] = 'i';
24      dfs(top1+1,top2,n+1);
25      k--;
26      st1[top1+1] = t;
27      }
28      if(st1[top1] == ch2[top2]){
29                   op[k++] = 'o';
30                     dfs(top1-1,top2+1,n);
31                     k--;
32      }
33 }
34      
35 int main(){
36     while(~scanf("%s%s",ch1,ch2)){
37           k=0;
38           len = strlen(ch1);
39           memset(st1,0,sizeof(st1));
40           printf("[\n");
41           dfs(0,0,0);
42           printf("]\n");
43     }
44     return 0;
45 }


总结:

对于能用深搜的题目,我们要分清楚当前所有的选择,并对当前所有的选择都要进行一次遍历,这样才能能将所有的情况都遍历一遍,寻找到最后的结果。

posted @ 2012-04-27 11:15  HNU_AlienForce  阅读(170)  评论(0)    收藏  举报