hdu1515

用栈来模拟操作,主要还是DFS

注意回溯条件,还有遍历失败后的操作就没什么了

#include<iostream>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
char b[200],b1[100],b2[100];//b[]保存路径
stack<char> ST;
int len1,len2;
int cmp( const void* c1,const void* c2)
{
	return *(char *)c1-*(char *)c2;
}
void dfs(int a1,int a2)
{
	if(a1==a2&&a1==len1)
	{
		for(int i=0;i<len1*2;i++)
			cout<<b[i]<<' ';
		cout<<endl;
		return ;
	}
	if(a1<=len1)
	{
		b[a1+a2]='i';
		ST.push(b1[a1]);
		dfs(a1+1,a2);
		ST.pop();//回溯时,记得将栈顶元素出栈
	}
	if(!ST.empty()&&a2<len1)
	{
	
		if(ST.top()==b2[a2])
		{	
			b[a1+a2]='o';
			ST.pop();
			dfs(a1,a2+1);
			ST.push((b2[a2]));//同样,记得要压回
		}
	}
	return ;
}
int main()
{
	char str1[100],str2[100];
	while(cin>>b1>>b2)
	{
		while(!ST.empty())
		{
			ST.pop();
		}
		int flag=0;
		len1=strlen(b1);
		len2=strlen(b2);
		if(len1!=len2)
		{
			flag=1;
		}
		else 
		{
			strcpy(str1,b1);
			strcpy(str2,b2);			
			qsort(str1,len1,sizeof(char),cmp);
			qsort(str2,len1,sizeof(char),cmp);
			if(!strcmp(str1,str2))//判断俩个字符串所含元素是否相同
			{
				b[0]='i';
				ST.push(b1[0]);
				cout<<'['<<endl;
				dfs(1,0);
				cout<<']'<<endl;
			}
			else flag=1;
		}
		if(flag)
         cout<<'['<<endl<<']'<<endl;
	}
	return 0;
}

原文地址:https://www.cnblogs.com/nanke/p/2124987.html