uva656 Optimal Programs

Source: Internet
Author: User

Optimal Programs

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

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

The programs you produce'll has to run on a stack based machine, which supports only five commands: ADD,SUB , MUL, DIV and DUP. The first four commands pops the top elements from the stack and push their sum, difference, product or integer Quotien T1, respectively, on the stack. The DUP command pushes a additional copy of the Top-most stack element on the stack.

So if the commands is applied to a stack with the both top elements a and b (shown to the left), the Res Ulting stacks look as follows:

At the beginning of the execution of a, the stack would 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 is three cases in which the stack machine enters a 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 lines contains NIntegers each:in the first line (all different), and the second line. The numbers is no more than than 30000 in absolute value.

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

Output you is to find the shortest program, that computes a function F, such that F( x I) = y IFor all. This implies, the program for you, output may not enter a error state if executed on the inputs x I(Although it may enter a error state to other inputs). Consider only programs that has at most statements.

For each function description, output first the number of the description. Then print out the se-quence of commands, 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 in most ten 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
41 2 3 40-2-6-1231 2 31 11 19981199819980
Sample Output
Program 1DUP DUP MUL subprogram 2ImpossibleProgram 3Empty sequence
Footnotes
... quotient1
This
is corresponds to/applied to the integers in C + +, and DIV in Pascal.

//http://uva.onlinejudge.org/external/6/656.html#include <cstdio>#include<cstring>#include<cmath>#include<stack>#include<queue>using namespacestd;Const intmaxn=Ten+5;Const Char* tr[] = {"ADD","DIV","DUP","MUL","SUB"};enumop_e {ADD, DIV, DUP, MUL, SUB};structState {State () {memset (path,0,sizeof(path)); Pathn=0; } Stack<int>s; intPATH[MAXN]; intPathn;} ans;intX[MAXN], Y[MAXN];intN;voidinit () { for(intI=0; i<n; i++) scanf ("%d", x+i);  for(intI=0; i<n; i++) scanf ("%d", y+i);}//return True if trans is valid and modified TBOOLTrans (state& T,inti) {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; intA=S.top (); if(I==div && a==0)return false; //the size of the current stack minus the size of the remaining steps, if greater than 1, the description will never reach the target (assuming that the following is not the DUP command, then the stack size is minus one)    intLen=s.size ()-(Ten-t.pathn); if(len>1)return false; //OK, now all options is valid    if(i==DUP)        {S.push (a); T.path[t.pathn++]=i; return true; } s.pop ();//Pop a    intb=s.top (); S.pop (); Switch(i) { CaseAdd:s.push (A+b);  Break;  CaseSub:s.push (b-a);  Break;  CaseMul:s.push (b*a);  Break;  CaseDiv:s.push (b/a);  Break; }    if(ABS (S.top ()) >30000)        return false; T.path[t.pathn++]=i; return true;}BOOLcheckothers () { for(inti =1; I < n; i++) {State T;        T.s.push (X[i]);  for(intj=0; j<ans.pathn; J + +)        {            if(!Trans (T, Ans.path[j]))return false; }        if(T.s.top ()! =Y[i])return false; }    return true;}BOOLBFs () {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; }        //It 's already 10 and can't be added anymore.        if(front.pathn==Ten)            Continue;  for(inti=add;i<=sub;i++) {State T=Front; if(trans (T, i)) Q.push (t); }    }    return false;}voidsolve () {if(BFS ()) {if(Ans.pathn = =0) printf ("Empty sequence\n"); Else {               for(inti =0; I < ans.pathn-1; i + +) printf ("%s", Tr[ans.path[i]]); printf ("%s\n", Tr[ans.path[ans.pathn-1]]); }      }      Elseprintf"impossible\n"); printf ("\ n"); }  intMain () {#ifndef Online_judge freopen ("./uva656.in","R", stdin);#endif    intKase=0;  while(SCANF ("%d", &n)!=eof &&N) {init (); printf ("Program %d\n", ++Kase);    Solve (); }    return 0;}

uva656 Optimal Programs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.