栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

NOJ算法实验二-1143-字母转换

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

NOJ算法实验二-1143-字母转换

题目描述:
通过栈交换字母顺序。给定两个字符串,要求所有的进栈和出栈序列(i表示进栈,o表示出栈),使得字符串1在求得的进出栈序列的操作下,变成字符串2。输出结果需满足字典序。例如TROT 到 TORT:
[
i i i i o o o o
i o i i o o i o
]


这一题用到的算法为回溯,其中有一些简单的栈的应用,思路难度不大,但是要注意细节。

首先要设立三个字符串,分别是start(输入),mid(栈)和ans(由出栈构成的字符串),每一次可以入栈(start的一个字符压入mid)或者出栈(mid的一个字符压入ans),然后将ans与end(要求转化成的最终字符串)进行局部比较,判断是否继续,这也是一个简单的剪枝。

事实上,只要对栈较为熟悉,这一题应能不那么困难地完成。特别地,题目有多组数据,应该使用while/scanf结构输入。

代码如下:

#include 
#include 
#include 

typedef struct
{
	char ch[1000];
	int top;
	int last;
} chStack;

typedef struct
{
	int operation[1000];
	int top;
} inStack;

chStack start;
chStack end;
chStack mid;
chStack ans;
inStack op;

void dfs();
int issame();
void output();

int main()
{
	//input and init
	while (scanf("%s%s", start.ch, end.ch) != EOF)
	{
		start.last = strlen(start.ch) - 1;
		end.last = strlen(end.ch) - 1;

		start.top = -1;
		end.top = -1;
		mid.top = -1;
		ans.top = -1;
		op.top = -1;

		printf("[n");
		dfs();
		printf("]n");

	}
}


void dfs()
{
	if (ans.top == end.last && issame())
	{
		output();
	}
	
	if (start.top < start.last)
	{
		start.top++;

		mid.top++;
		mid.ch[mid.top] = start.ch[start.top];

		op.top++;
		op.operation[op.top] = 1;

		dfs();

		
		op.top--;

		mid.top--;

		start.top--;
	}
	
	if (mid.top != -1)
	{
		ans.top++;
		ans.ch[ans.top] = mid.ch[mid.top];

		mid.top--;

		op.top++;
		op.operation[op.top] = 0;

		
		if (issame())
		{
			dfs();
		}

		
		op.top--;

		mid.top++;
		mid.ch[mid.top] = ans.ch[ans.top];

		ans.top--;
	}
}

int issame()
{
	int i;
	for (i = 0; i <= ans.top; i++)
	{
		if (ans.ch[i] != end.ch[i])
		{
			return 0;
		}
	}
	return 1;
}

void output()
{
	int i;
	for (i = 0; i <= op.top; i++)
	{
		if (op.operation[i] == 1)
		{
			printf(" i" + !i);//这里使用了简单的技巧,使得行首行尾没有空格
		}
		else
		{
			printf(" o" + !i);
		}
	}
	printf("n");
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/291059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号