ZOJ 1004 Anagrams by Stack(DFS+数据结构)

Anagrams by Stack

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4

题目大意:输入两个字符串序列,判断能否通过对第一个字符串进行进栈出栈操作得到第二个字符串,若能则输出所有能达到的进出栈操作过程。我通过全排列每得到一组操作过程,则用函数按照这个操作过程,判断能否得到第二个字符串,若能则表明此操作过程可行,输出。

代码如下:

 1 # include<iostream>
 2 # include<stack>
 3 # include<vector>
 4 # include<algorithm>
 5 using namespace std;
 6 
 7 string str1,str2;
 8 stack<char> p;
 9 vector<char> ans;
10 int len;
11 
12 void print(){
13     for(int i =0; i<ans.size(); i++)
14         cout<<ans[i]<<" ";  //注意空格
15     cout<<endl;
16 }
17 
18 void dfs(int x,int y){
19     if(x==len && y==len)
20         print();
21     if(x+1<=len){
22         p.push(str1[x]);
23         ans.push_back('i');
24         dfs( x+1 , y);
25         p.pop();
26         ans.pop_back();
27     }
28     if(y+1<=x && y+1<=len &&p.top() == str2[y]){
29         char temp = p.top();
30         p.pop();
31         ans.push_back('o');
32         dfs(x,y+1);
33         p.push(temp);
34         ans.pop_back();
35     }
36 }
37 
38 int main(){
39     while(cin >> str1 >> str2){
40         len =str1.length();
41         string t1 = str1, t2 = str2;
42         sort(t1.begin(),t1.end());
43         sort(t2.begin(),t2.end());
44         cout<<"["<<endl;
45         if(t1 == t2){
46             dfs(0,0);
47         }
48         cout<<"]"<<endl;
49     }
50     return 0;
51 }
原文地址:https://www.cnblogs.com/acm-bingzi/p/3258815.html