#include #include #include #define MAX_BUFFER 2048 char command[20]; int x[40000], y[40000]; int N; int LC; int simulate(int lc, int x, int y) { int stack[50]; int i, sp = 1; if (lc == 0) return 0; stack[0] = x; for(i = 0; i < lc; i++) { /* printf("P: %d %d ", stack[sp-1],sp);*/ switch (command[i]) { case 'E':{stack[sp] = stack[sp-1]; sp++; }; break; case 'A': {sp--; if (sp <= 1) return 0; stack[sp-1] = stack[sp-1] + stack[sp];}; break; case 'S': {sp--; if (sp <= 1) return 0; stack[sp-1] = stack[sp-1] - stack[sp]; }; break; case 'M': {sp--; if (sp <= 1) return 0; stack[sp-1] = stack[sp-1] * stack[sp]; }; break; case 'D': {sp--; if (sp <= 1) return 0; if (!stack[sp]) return 0; stack[sp-1] = stack[sp-1] / stack[sp]; }; break; } if ((stack[sp-1] > 30000) || (stack[sp-1] <-30000)) return 0; } if ((sp == 1) && (stack[sp-1] == y)) { return 1; } return 0; } int add_command(int lc, int dups, int ops) { int i, ok = 1; if (lc > LC) return 0; for(i = 0; i < N; i++) { if (!simulate(lc, x[i], y[i])) ok = 0; } if (ok) return lc; /*printf("## %d %d\n", dups, ops); fflush(stdout); */ if (dups < 5) { command[lc] = 'E'; ok = add_command(lc + 1, dups + 1, ops); if (ok) return ok; } if (ops < dups) { command[lc] = 'A'; ok = add_command(lc + 1, dups, ops + 1); if (ok) return ok; command[lc] = 'D'; ok = add_command(lc + 1, dups, ops + 1); if (ok) return ok; command[lc] = 'M'; ok = add_command(lc + 1, dups, ops + 1); if (ok) return ok; command[lc] = 'S'; ok = add_command(lc + 1, dups, ops + 1); if (ok) return ok; } return 0; } int main() { FILE *fin; char buffer[MAX_BUFFER], b2[MAX_BUFFER], *p1, *p2, *p3; int i, j, k, l, SEQ=1; char c, c1, c2; int ok; fin = fopen("optimal.in", "r"); again: fscanf(fin, "%d", &N); if (!N) return 0; printf("Program %d\n", SEQ++); for(i = 0; i < N; i++) fscanf(fin, "%d", &x[i]); l = 0; for(i = 0; i < N; i++) { fscanf(fin, "%d", &y[i]); if (y[i] == x[i]) l++; } if (l == N) { printf("Empty sequence\n\n"); goto again; } /* for(i = 0; i < lc; i++) { for(j = 0; j <= i; j++) { } }*/ /*strcpy(command,"PPMS"); printf("S: %d\n",simulate(4,4,-12)); */ for(j = 0; j < 10; j++) { LC = j; ok = add_command(0, 0, 0); if (ok) { for(i = 0; i < ok; i++) { switch (command[i]) { case 'E': printf("DUP "); break; case 'A': printf("ADD "); break; case 'M': printf("MUL "); break; case 'D': printf("DIV "); break; case 'S': printf("SUB "); break; } } printf("\n\n"); goto again; } } printf("Impossible\n\n"); goto again; return 0; }