Optimal Programs

As you know, writing programs is often far from being easy. Things become even harder if your programs have to be as fast as possible. And sometimes there is reason for them to be. Many large programs such as operating systems or databases have ``bottlenecks'' - segments of code that get executed over and over again, and make up for a large portion of the total running time. Here it usually pays to rewrite that code portion in assembly language, since even small gains in running time will matter a lot if the code is executed billions of times.

In this problem we will consider the task of automating the generation of optimal assembly code. Given a function (as a series of input/output pairs), you are to come up with the shortest assembly program that computes this function.

The programs you produce will have to run on a stack based machine, that supports only five commands: ADD,SUB, MUL, DIV and DUP. The first four commands pop the two top elements from the stack and push their sum, difference, product or integer quotient1 , respectively, on the stack. The DUP command pushes an additional copy of the top-most stack element on the stack.

So if the commands are applied to a stack with the two top elements a and b (shown to the left), the resulting stacks look as follows:

At the beginning of the execution of a program, the stack will contain a single integer only: the input. At the end of the computation, the stack must also contain only one integer; this number is the result of the computation.

There are three cases in which the stack machine enters an error state:

  • A DIV-command is executed, and the top-most element of the stack is 0.
  • A ADD, SUB, MUL or DIV-command is executed when the stack contains only one element.
  • An operation produces a value greater than 30000 in absolute value.

Input

The input consists of a series of function descriptions. Each description starts with a line containing a single integer n (), the number of input/output pairs to follow. The following two lines contains nintegers each: in the first line (all different), and in the second line. The numbers will be no more than 30000 in absolute value.

The input is terminated by a test case starting with n = 0. This test case should not be processed.

Output

You are to find the shortest program that computes a function f , such that f(xi) = yi for all . This implies that the program you output may not enter an error state if executed on the inputs xi(although it may enter an error state for other inputs). Consider only programs that have at most 10 statements.

For each function description, output first the number of the description. Then print out the se- quence of commands that make up the shortest program to compute the given function. If there is more than one such program, print the lexicographically smallest. If there is no program of at most 10 statements that computes the function, print the string ``Impossible''. If the shortest program consists of zero commands, print ``Empty sequence''.

Output a blank line after each test case.

Sample Input

4
1 2 3 4
0 -2 -6 -12
3
1 2 3
1 11 1998
1
1998
1998
0

Sample Output

Program 1
DUP DUP MUL SUB Program 2
Impossible Program 3
Empty sequence

Footnotes
... quotient1
This corresponds to / applied to two integers in C/C++, and DIV in Pascal.

 

 

//http://uva.onlinejudge.org/external/6/656.html
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
const int maxn=10+5; const char * tr[] = {"ADD", "DIV", "DUP", "MUL", "SUB"};
enum op_e { ADD, DIV, DUP, MUL, SUB}; struct State {
State()
{
memset(path, 0, sizeof(path));
pathn=0;
}
stack<int> s;
int path[maxn];
int pathn;
}ans; int x[maxn], y[maxn];
int n; void init()
{
for(int i=0; i<n; i++)
scanf("%d", x+i);
for(int i=0; i<n; i++)
scanf("%d", y+i);
} // return true if trans is valid and modified t
bool trans(State& t, int i)
{
stack<int> &s = t.s;
//A ADD, SUB, MUL or DIV-command is executed when the stack contains only one element.
if(i!=DUP && s.size()==1) return false; int a=s.top();
if(i==DIV && a==0) return false; //当前栈的大小减去剩余步骤的大小,如果大于1,说明永远达不到目标(假设后面不是dup命令,则栈大小都是减一)
int len=s.size()-(10-t.pathn);
if(len>1) return false; //ok, now all options are valid
if(i==DUP)
{
s.push(a);
t.path[t.pathn++]=i;
return true;
} s.pop();//pop a
int b=s.top(); s.pop(); switch(i)
{
case ADD:
s.push(a+b);
break;
case SUB:
s.push(b-a);
break;
case MUL:
s.push(b*a);
break;
case DIV:
s.push(b/a);
break;
}
if(abs(s.top())>30000)
return false; t.path[t.pathn++]=i;
return true;
} bool checkOthers()
{
for (int i = 1; i < n; i++)
{
State t;
t.s.push(x[i]);
for(int j=0; j<ans.pathn; j++)
{
if(!trans(t, ans.path[j]))
return false;
}
if(t.s.top()!=y[i])
return false;
}
return true;
} bool bfs()
{
queue<State> q; ans = State();
State state;
state.s.push(x[0]);
q.push(state); while(!q.empty())
{
State front = q.front(); q.pop(); if(front.s.size()==1 && front.s.top()==y[0])
{
ans = front;
if(checkOthers())
return true;
} //已经10个了,不能再添加了
if(front.pathn==10)
continue; for(int i=ADD;i<=SUB;i++)
{
State t=front;
if(trans(t, i))
q.push(t);
}
}
return false;
} void solve() {
if (bfs()) {
if (ans.pathn == 0) printf("Empty sequence\n");
else {
for (int i = 0; i < ans.pathn - 1; i ++)
printf("%s ", tr[ans.path[i]]);
printf("%s\n", tr[ans.path[ans.pathn - 1]]);
}
}
else printf("Impossible\n");
printf("\n");
} int main()
{
#ifndef ONLINE_JUDGE
freopen("./uva656.in", "r", stdin);
#endif
int kase=0;
while(scanf("%d", &n)!=EOF && n)
{
init();
printf("Program %d\n", ++kase);
solve();
}
return 0;
}

uva656 Optimal Programs的更多相关文章

  1. POJ题目细究

    acm之pku题目分类 对ACM有兴趣的同学们可以看看 DP:  1011   NTA                 简单题  1013   Great Equipment     简单题  102 ...

  2. BFS广搜题目(转载)

    BFS广搜题目有时间一个个做下来 2009-12-29 15:09 1574人阅读 评论(1) 收藏 举报 图形graphc优化存储游戏 有时间要去做做这些题目,所以从他人空间copy过来了,谢谢那位 ...

  3. 泡泡一分钟:Optimal Trajectory Generation for Quadrotor Teach-And-Repeat

    张宁 Optimal Trajectory Generation for Quadrotor Teach-And-Repeat链接:https://pan.baidu.com/s/1x0CmuOXiL ...

  4. 最优运输(Optimal Transfort):从理论到填补的应用

    目录 引言 1 背景 2 什么是最优运输? 3 基本概念 3.1 离散测度 (Discrete measures) 3.2 蒙日(Monge)问题 3.3 Kantorovich Relaxation ...

  5. Optimal Flexible Architecture(最优灵活架构)

    来自:Oracle® Database Installation Guide 12_c_ Release 1 (12.1) for Linux Oracle base目录命名规范: /pm/s/u 例 ...

  6. Leetcode: Optimal Account Balancing

    A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for ...

  7. some simple recursive lisp programs

    1. Write a procedure count-list to count the number of elements in a list (defun count-list (numbers ...

  8. (待续)C#语言中的动态数组(ArrayList)模拟常用页面置换算法(FIFO、LRU、Optimal)

    目录 00 简介 01 算法概述 02 公用方法与变量解释 03 先进先出置换算法(FIFO) 04 最近最久未使用(LRU)算法 05 最佳置换算法(OPT) 00 简介 页面置换算法主要是记录内存 ...

  9. PLoP(Pattern Languages of Programs,程序设计的模式语言)

    2014/8/1 12:24:21潘加宇 http://www.umlchina.com/News/Content/340.htmPloP大会2014即将举行 PLoP(Pattern Languag ...

随机推荐

  1. Mockjs生成Vue数据表格

    1.npm install mockjs --save 2.在src文件下建mock.js文件 3.mock.js文件文件内容 //引入mockjs import Mock from 'mockjs' ...

  2. NIO--SocketChannel发送HTTP请求

    import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChanne ...

  3. Win7-U盘安装出现"We were unable to copy your files. "

    使用Windows 7 USB/DVD Download Tool时,提示We were unable to copy your files. Please check your USB device ...

  4. saveFile()方法

    saveFile的原理就是将流写入到需要写入的文件,通过可以用“FileOutputStream”创建文件实例,之后过“OutputStreamWriter”流的形式进行存储,举例:public vo ...

  5. boost准模板库内存管理中pool和object_pool的使用

    首先,在敲代码之前,必须改动一个问题.要不然,无法链接: boost安装文件夹:D:\boost.       找到D:\boost\boost_1_55_0\include\boost-1_55\b ...

  6. 深入分析 iBATIS 框架之系统架构与映射原理

    iBATIS 框架主要的类层次结构 总体来说 iBATIS 的系统结构还是比较简单的,它主要完成两件事情: 根据 JDBC 规范建立与数据库的连接: 通过反射打通 Java 对象与数据库参数交互之间相 ...

  7. Linux上的free命令简介

    每次使用free时都比较迷惑,对于上面的内容一直都不是很清楚,今天仔细查了以下,和大家一起分享以下: 先看一下free的运行结果: free打印出的内存信息主要分为两种,一种是安装的内存,一种是用磁盘 ...

  8. 【转】【Linux】Linux 下zip包的压缩与解压

    linux zip 命令详解 功能说明:压缩文件. 语 法:zip [-AcdDfFghjJKlLmoqrSTuvVwXyz$][-b <工作目录>][-ll][-n <字尾字符串& ...

  9. 负margin应用案例几则(转载+总结)

    (一)自适应布局——左栏改右栏 这里先写个一列固定列宽,另一列自适应的两列布局,效果图: 侧栏移至右边,效果图: 其HTML <div class="wrap"> &l ...

  10. 【UVa】Partitioning by Palindromes(dp)

    http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=27&page=sh ...