Problem G
字母转换
时限:1000ms 内存限制:10000K 总时限:3000ms
描述:
通过栈交换字母顺序。给定两个字符串,要求所有的进栈和出栈序列(i表示进栈,o表示出栈),使得字符串2在求得的进出栈序列的操作下,变成字符串1。输出结果需满足字典序。例如TROT 到 TORT:
[
i i i i o o o o
i o i i o o i o
]
输入:
给定两个字符串,第一个字符串是源字符串,第二个字符是目标目标字符串。
输出:
所有的进栈和出栈序列,输出结果需满足字典序
输入样例:
madam
adamm
bahama
bahama
long
short
eric
rice
输出样例:
[ 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 ]
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
char s1[100], s2[100];
char res[200];
void display()
{
for (int i = 0; i < strlen(res)-1; ++i)
{
cout << res[i] << " ";
}
cout << res[strlen(res)-1] << endl;
}
void dfs(stack<char> s, int m, int n, int index) //s为当前栈,m为s1下标,n为s2下标,index为res下标
{
//递归终止条件1:s1,s2 都遍历完,且栈为空,表示已经找到了一组满足条件的进栈出栈序列
if(m >= strlen(s1) && n >= strlen(s2) && s.empty())
{
display();
return;
}
//递归终止条件2:s1已经遍历完,栈不为空,且栈顶元素不等于s2的指针所指的元素,即没找到满足条件的进栈出栈序列
if (m >= strlen(s1) && s.top() != s2[n])
{
return;
}
//栈空,或栈顶与s2的当前下标值不匹配,则s1当前下标值进栈,s1下标后移
if(s.empty() || s.top() != s2[n])
{
s.push(s1[m]);
res[index] = 'i';
dfs(s, m+1, n, index+1);
}
//栈顶与s2当前下标的值匹配
else
{
//分支1:进栈
s.push(s1[m]);
res[index] = 'i';
dfs(s, m+1, n, index+1);
s.pop(); //回溯
//分支2:出栈
s.pop();
res[index] = 'o';
dfs(s, m, n+1, index+1);
}
}
int main(int argc, char const *argv[])
{
while(cin >> s1 >> s2)
{
stack<char> s;
cout << "[" << endl;
dfs(s, 0, 0, 0);
cout << "]" << endl;
memset(s1,'\0',sizeof(s1));
memset(s2,'\0',sizeof(s2));
memset(res,'\0',sizeof(res));
}
return 0;
}