noj 1143 G 字母转换

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;
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值