zoukankan      html  css  js  c++  java
  • hdu 1515 Anagrams by Stack 栈 回溯

    http://acm.hdu.edu.cn/showproblem.php?pid=1515

     

    http://www.cnblogs.com/liuqidong/archive/2010/07/26/1785076.html

    本题并不是很难,就是输出所有能够目标WORD的可能。所以dfs+stack很容易解决。递归时有两种情况:

    第一:两个字符不相等(即栈顶字符与目标字符不相等);这种情况很容易处理,将匹配word的下一个字符入栈,指针向后挪已为继续递归。

    第二:两个字符相等(即栈顶字符与目标字符相等);这种情况有两种选择

          (1)字符出栈,并将目标word的指针向后挪一位,继续递归;

          (2)将匹配word的下一个字符入栈,指针向后挪一位,继续递归;

    每一次递归用path记录下来路径。当目标word的指针超过最后一位了,说明成功,此时将path输出。

     
    #include<stdio.h>
     #include<string.h>
    #include<stack>
    using namespace std;
    char str1[1005],str2[1005];int len1,len2;
    char path[2005];
     void test(int x,int y,stack<char> st,int t)
     {
          int j;
         if(y==len2)
         {
             printf("i ");
             for(j=0;j<t;j++)
                 printf("%c ",path[j]);
             printf("\n");
             return ;
         }
         if(st.empty ())
         {
             st.push(str1[x+1]);
             path[t]='i';
             test(x+1,y,st,t+1);
             st.pop();
             return ;
         }
         char cur=st.top ();
         if(x==len1 && cur!=str2[y])
             return ;
         if(cur!=str2[y])
         {
             st.push(str1[x+1]);
             path[t]='i';
             test(x+1,y,st,t+1);
             st.pop();
         }
         if(cur==str2[y])
         {
             st.push(str1[x+1]);
             path[t]='i';
             test(x+1,y,st,t+1);
             st.pop();
             st.pop();
             path[t]='o';
             test(x,y+1,st,t+1);
             st.push(str1[x]);
         }
         return ;
     }
     int main()
     {
         int i,j;
         while(scanf("%s%s",str1,str2)!=EOF)
         {
             len1=strlen(str1);
             len2=strlen(str2);
             printf("[\n");
             if(len1<len2)
             {
                 printf("]\n");
                 continue;
             }
             stack<char> st;
             st.push(str1[0]);
             test(0,0,st,0);
             printf("]\n");
         }
         return 0;
     }
  • 相关阅读:
    codevs 2632 非常好友
    codevs 1213 解的个数
    codevs 2751 军训分批
    codevs 1519 过路费
    codevs 1503 愚蠢的宠物
    codevs 2639 约会计划
    codevs 3369 膜拜
    codevs 3135 River Hopscotch
    数论模板
    JXOJ 9.7 NOIP 放松模拟赛 总结
  • 原文地址:https://www.cnblogs.com/zxj015/p/2740255.html
Copyright © 2011-2022 走看看