最优程序

来源:互联网 发布:淘宝信用支付什么意思 编辑:程序博客网 时间:2024/05/21 11:14

        有一台只有一个数据栈的计算机,支持整数的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
原创粉丝点击