How can anagrams result from sequences of stack operations? There are twosequences of stack operators which can convert TROT to TORT:
[ i i i i o o o o i o i i o o i o ]
where i stands for Push and o standsfor Pop. Your program should, givenpairs of words produce sequences of stack operations which convert the firstword to the second.
Input
The input will consist of several lines of input. The first line of eachpair of input lines is to be considered as a source word (which does notinclude the end-of-line character). The second line (again, not includingthe end-of-line character) of each pair is a target word. The end of inputis marked by end of file.
Output
For each input pair, your program should produce a sorted list of validsequences of i and o which producethe target word from the source word.Each list should be delimited by
[ ]and the sequences should be printed in "dictionary order". Within eachsequence, each i and o isfollowed by a single space and each sequence isterminated by a new line.
Process
A stack is a data storage and retrieval structure permitting twooperations:
Pop - to retrieve the most recently pushed item
We will use the symbol i (in) for pushand o (out) for pop operations for aninitially empty stack of characters. Given an input word, some sequencesof push and pop operations are valid in that every character of the word isboth pushed and popped, and furthermore, no attempt is ever made to pop theempty stack. For example, if the word FOO is input, then the sequence:
i i o i o o | is valid, but |
i i o | is not (it's too short), neither is |
i i o o o i | (there's an illegal pop of an empty stack) |
Valid sequences yield rearrangements of the letters in an input word. Forexample, the input word FOO and the sequence i i o i o o produce theanagram OOF. So also would the sequence i i i o o o. Youare to write a program to input pairs of words andoutput all the valid sequences of i ando which will produce the second member of each pair from the first.
Sample Input
madam adamm bahama bahama long short eric rice
Sample Output
[ i i i i o o o i o o i i i i o o o o i o i i o i o i o i o o i i o i o i o o i o ] [ i o i i i o o i i o o o i o i i i o o o i o i o i o i o i o i i i o o o i o i o i o i o i o i o ] [ ] [ i i o i o i o o ]
用回溯法做的,回溯的是选择i或选择o
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack<char> s;
string in,out,stk,mod;
int length;
int dfs(int i,int j){
char tmp;
string outtmp,outstk;
if(mod.size()==out.size()){
if(mod==out) cout<<stk<<endl;
return 0;
}
if(i>2*in.size()+1){
return 0;
}
tmp=in[j];
outstk=stk;
stk+="i ";
s.push(tmp);
dfs(i+1,j+1);
stk=outstk;
s.pop();
if(!s.empty()){
tmp=s.top();
outtmp=out;
outstk=stk;
out+=tmp;
stk+="o ";
s.pop();
dfs(i+1,j);
stk=outstk;
out=outtmp;
s.push(tmp);
}
}
int main(){
while(cin>>in){
out="",stk="";
while(!s.empty()){
s.pop();
}
cin>>mod;
cout<<'['<<endl;
dfs(0,0);
cout<<']'<<endl;
}
return 0;
}