最优程序

        有一台只有一个数据栈的计算机,支持整数的5种运算:ADD、SUB、MUL、DIV、DUP。假设栈顶的三个元素分别为a、b、c,则5种运算的效果依次如下。

ADD:a和b依次出栈,计算a + b,把结果压栈

SUB:a和b依次出栈,计算a - b,把结果压栈

MUL:a和b依次出栈,计算a * b,把结果压栈

DIV:a和b依次出栈,计算b / a并向下取整,把结果压栈。

DUP:a出栈,再连续把两个a压栈。

遇到以下情况之一,机器会产生错误;执行DIV操作时,栈顶元素为0;执行ADD、SUB、MUL、DIV操作时,栈里只有一个元素;运算结果的绝对值大于30000。

        给出n个整数对(ai, bi)(ai互不相同),你的任务时设计一个最短的程序,使得杜宇1和n之间的所有i,如果程序执行前栈中只有一个元素ai,则执行后栈顶元素时bi .n<=5

 

分析:经典的BFS题目!

#include <iostream>
using namespace std;
const int maxn = 1000;

int a, b;

struct node
{
	int pos;
	int s[maxn];
	int pre;
	int op;
};
node p[maxn];

void print(node w)
{
	if (w.pre != -1)
		print(p[w.pre]);

	if (w.op == 0)
		printf("+\n");
	else if (w.op == 1)
		printf("-\n");
	else if (w.op == 2)
		printf("*\n");
	else if (w.op == 3)
		printf("/\n");
	else if (w.op == 4)
		printf("dup\n");
	else if (w.op == -1)
		printf("%d\n", a);
}

void bfs()
{
	int head, end;
	p[head = end = 0].pos = 1;
	p[head].s[0] = a;
	p[head].pre = -1;
	p[end++].op = -1;

	while (head < end)
	{
		node w = p[head];

		if (w.s[w.pos - 1] == b)
		{
			print(w);
			return ;
		}

		if (w.pos > 1)
		{
			node m = w;
			int x1 = m.s[--m.pos];
			int x2 = m.s[--m.pos];
			m.s[m.pos++] = x1 + x2;
			m.pre = head;
			m.op = 0;
			p[end++] = m;
		}

		if (w.pos > 1)
		{
			node m = w;
			int x1 = m.s[--m.pos];
			int x2 = m.s[--m.pos];
			m.s[m.pos++] = x2 - x1;
			m.pre = head;
			m.op = 1;
			p[end++] = m;
		}

		if (w.pos > 1)
		{
			node m = w;
			int x1 = m.s[--m.pos];
			int x2 = m.s[--m.pos];
			m.s[m.pos++] = x1 * x2;
			m.pre = head;
			m.op = 2;
			p[end++] = m;
		}

		if (w.pos > 1 && w.s[w.pos - 1])
		{
			node m = w;
			int x1 = m.s[--m.pos];
			int x2 = m.s[--m.pos];
			m.s[m.pos++] = x2 / x1;
			m.pre = head;
			m.op = 3;
			p[end++] = m;
		}

		if (w.pos > 0)
		{
			node m = w;
			int x = m.s[--m.pos];
			m.s[m.pos++] = x;
			m.s[m.pos++] = x;
			m.pre = head;
			m.op = 4;
			p[end++] = m;
		}

		++head;
	}
}

int main()
{
	while (scanf("%d %d", &a, &b))
	{
		bfs();
	}

	return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值