Anagrams by Stack

//		DJ.W	2013.4.20	
//问题描述 : Anagrams by Stack
//			 http://acm.suse.edu.cn/index.php?mod=problem&id=1056
//算法思路: 用回溯法搜索
//开发环境:  vs2008

#include "stdafx.h"
#include <iostream>
using namespace std;
#include<string>
#include<vector>

//栈结构
class stack
{
public:
	stack(int n=30)
	{
		m_maxnum = n;
		m_pdata = new char[n];
		m_top = -1;
	}

	~stack()
	{
		delete []m_pdata;
		m_pdata = 0;
	}

	void reset()
	{
		m_top = -1;
	}

	bool push(char c)
	{
		if (m_top == m_maxnum-1)
			return false;
	
		m_pdata[++m_top] = c;
		return true;
	}

	bool pop(char* c)
	{
		if(m_top == -1)
			return false;

		*c = m_pdata[m_top--];
		return true;
	}

	bool pop()
	{
		if(m_top == -1)
			return false;

		--m_top;
		return true;
	}

	void addtop(int n)
	{
		m_top += n;
	}
private:
	char* m_pdata;
	int m_top;
	int m_maxnum;
};

//为了减少参数 使用全局变量
stack s;
char sztemp[100] = {0};	//存放不断弹出得到的临时字符串
char szpath[100] = {0};	//存放弹出和弹入路径
int index = 0;

void traceback(const string& strOrigin, const string& strTarget, int i, int j)
 {
	 //如果源字符串已经全部弹入 那么直接全部弹出
	if (i == strOrigin.size())
	{
		char c;
		int t = index;
		int tj = j;
		//全部弹出 记录路径
		while (s.pop(&c))
		{
			sztemp[tj++] = c;
			szpath[t++] = 'o';
			szpath[t++] = ' ';
		}
		
		//恢复栈情形
		s.addtop(tj-j);

		//如果和目标字符串一致 输出路径
		if (strTarget.compare(sztemp) == 0)
			cout<<szpath<<endl;

		return ;
	}

	//递归左子树 弹入
	if (s.push(strOrigin[i]))
	{
		//路径记录
		szpath[index++] = 'i';
		szpath[index++] = ' ';
		//进入左子树
		traceback(strOrigin, strTarget, i+1, j);
		//环境恢复
		index -= 2;
		s.pop();
	}

	//递归右子树 弹出
	char c;
	if (s.pop(&c))
	{
		//路径记录
		szpath[index++] = 'o';
		szpath[index++] = ' ';
		sztemp[j] = c;
		//进入右子树
		traceback(strOrigin, strTarget, i, j+1);
		//环境恢复
		s.push(c);
		index -= 2;
	}
	
}

int main()
{
	vector<string> v;
	string str;
	//记录字符串对 直到遇到文件结束符
	while(cin>>str)
	{
		v.push_back(str);
		string str;
		cin>>str;
		v.push_back(str);
	}
	vector<string>::iterator iter=v.begin();
	for(; iter<v.end()-1; iter+=2)
	{
		//在每次使用之前 要对全局变量进行重新初始化
		index = 0;
		memset(sztemp, 0, sizeof(sztemp));
		memset(szpath, 0, sizeof(szpath));
		s.reset();
		cout<<"["<<endl;
		traceback(*iter, *(iter+1), 0, 0);
		cout<<"]"<<endl;
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值