uva656 Optimal Programs

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;
}
时间: 2024-11-05 18:45:08

uva656 Optimal Programs的相关文章

UVA - 656 Optimal Programs 暴力

题目大意:刚开始栈中有一个数字,要求你经过一定的操作后,栈中最后保留下来的数等于所给的数. 解题思路:纯暴力,但要加上剪枝 1.当前的操作步数中,DUP的次数要大于等于其他操作的和 2.判断的时候,只有操作次数为偶数,且DUP的次数等于其他操作次数的和 #include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<stack> #include<

zoj题目分类

饮水思源---zoj 转载自:http://bbs.sjtu.edu.cn/bbscon,board,ACMICPC,file,M.1084159773.A.html 注:所有不是太难的题都被归成了“简单题”,等到发现的时候已经太晚了,我太死脑筋 了……:( 有些题的程序我找不到了,555……:( SRbGa的题虽然都很经典……但是由于其中的大部分都是我看了oibh上的解题报告后做 的,所以就不写了…… 题目排列顺序没有规律……:( 按照个人感觉,最短路有的算做了DP,有的算做了图论. 有些比较

wewe

BFS广搜题目有时间一个个做下来 2009-12-29 15:09 1574人阅读 评论(1) 收藏 举报 图形graphc优化存储游戏 有时间要去做做这些题目,所以从他人空间copy过来了,谢谢那位大虾啦. pku 1175 Starry Night 题目地址:http://acm.pku.edu.cn/JudgeOnline/problem?id=1175 解法:BFS,要注意的是如何判断图形是一样的,我的做法就是计算每两个点的距离之和. 看:http://hi.baidu.com/doxi

我你就报报我好

http://www.tudou.com/programs/view/gws5_W9LBOY/e0878.htmlhttp://www.tudou.com/programs/view/svb2E3asrwo/j8744.htmlhttp://www.tudou.com/programs/view/iZs6vuetaJM/d542n.htmlhttp://www.tudou.com/programs/view/l2tsMkkhuzU/5FSAS.htmlhttp://www.tudou.com/p

爱情是个奇迹

http://www.tudou.com/programs/view/0GBAt_FO_Hg/7kudM.htmlhttp://www.tudou.com/programs/view/cLzaXAGz-e4/Mudxd.htmlhttp://www.tudou.com/programs/view/JKZug-f69Z8/0unpZ.htmlhttp://www.tudou.com/programs/view/UcUo3ecyz0Y/Z4976.htmlhttp://www.tudou.com/p

POJ-2112 Optimal Milking(最大流)未完待续~

1 #include <cstdio> 2 #include <cmath> 3 #include <cstdlib> 4 #include <cstring> 5 #include <queue> 6 #include <stack> 7 #include <vector> 8 #include <iostream> 9 #include "algorithm" 10 #define me

codeforces 710B B. Optimal Point on a Line(数学)

题目链接: B. Optimal Point on a Line 题意: 给出n个点,问找出一个点使得这个点到所有的点的距离和最小; 思路: 所有点排序后的中位数;这是一个结论; AC代码: #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <bits/stdc++.h> #in

POJ 2112 Optimal Milking

Optimal Milking Time Limit: 2000ms Memory Limit: 30000KB This problem will be judged on PKU. Original ID: 211264-bit integer IO format: %lld      Java class name: Main FJ has moved his K (1 <= K <= 30) milking machines out into the cow pastures amon

UVAoj 348 - Optimal Array Multiplication Sequence

1 /* 2 题意:矩阵相乘的最少的步数 3 dp[i][j]=min(dp[i][j], dp[i][k]+dp[k+1][j]+num[i-1]*num[k]*num[j]); 4 表示的是第i个矩阵到第j个矩阵相乘的最少步数 5 sign[i][j]表示的是第i个矩阵到第j个矩阵相乘的最少步数是由第i个矩阵到第sign[i][j]个矩阵相乘最少步数 6 和第sign[i][j]+1个矩阵到第j个矩阵相乘最少步数的得到的最小值! 7 */ 8 #include<iostream> 9 #i