http://acm.pku.edu.cn/JudgeOnline/problem?id=1049
Код:
#include <stdio.h> #define __DEBUG__ #undef __DEBUG__ #define WORDWIDTH 4 #define ADDRWIDTH 8 #define MEMSIZE 256 typedef enum { LD , /* LD x A = memory[x] */ ST , /* ST x memory[x] = A */ SWP , /* SWP swap(A, B) */ ADD , /* ADD A = low(A + B), B = high(A + B) */ INC , /* INC A = A + 1 */ DEC , /* DEC A = A - 1 */ BZ , /* BZ x if(A == 0) pc = x */ BR , /* BR x pc = x */ STP /* STP stop the program */ } Instruction; unsigned int accuA; unsigned int accuB; unsigned int pc; unsigned int memory[MEMSIZE]; FILE * inputFile; FILE * outputFile; int ReadMemory (void); void Execute (void); void PrintMemory (void); int InitInput (void); void Cleanup (void); int main(void) { if(InitInput()) return 1; while(1) { if(!ReadMemory()) break; Execute(); PrintMemory(); } Cleanup(); return 0; } int ReadMemory(void) { char ch; int i; ch = fgetc(inputFile); while((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F')) ch = fgetc(inputFile); if(ch == '8') return 0; for(i = 1; i < MEMSIZE; ) { ch = fgetc(inputFile); if(ch >= '0' && ch <= '9') memory[i++] = ch - '0'; else if(ch >= 'A' && ch <= 'F') memory[i++] = ch - 'A' + 10; } return 1; } void Execute(void) { unsigned int instr; unsigned int low; unsigned int high; unsigned int opr; unsigned int sum; int finished = 0; accuA = 0; accuB = 0; pc = 0; while(!finished) { instr = memory[pc++]; switch(instr) { case LD : high = memory[pc++]; low = memory[pc++]; opr = (high << WORDWIDTH) + low; accuA = memory[opr]; break; case ST : high = memory[pc++]; low = memory[pc++]; opr = (high << WORDWIDTH) + low; memory[opr] = accuA; break; case SWP: accuA ^= accuB ^= accuA ^= accuB; break; case ADD: sum = (accuA + accuB) % 0x100; accuA = sum & 0x0f; accuB = (sum & 0xf0) >> WORDWIDTH; break; case INC: if(++accuA == 0x10) accuA = 0x0; break; case DEC: if(accuA == 0x0) accuA = 0xf; else accuA--; break; case BZ : high = memory[pc++]; low = memory[pc++]; opr = (high << WORDWIDTH) + low; if(accuA == 0x0) pc = opr; break; case BR : pc = memory[pc + 1]; break; case STP: finished = 1; break; } } } void PrintMemory(void) { int i; for(i = 0; i < MEMSIZE; i++) if(memory[i] < 10) fprintf(outputFile, "%d", memory[i]); else fprintf(outputFile, "%c", memory[i] - 10 + 'A'); fprintf(outputFile, "\n"); fflush(outputFile); } int InitInput(void) { #ifdef __DEBUG__ inputFile = fopen("input.txt" , "r"); outputFile = fopen("output.txt", "w"); if(inputFile == NULL) { printf("Cannot open input file.\n"); return 1; } if(outputFile == NULL) { printf("Cannot open output file.\n"); return 1; } #else inputFile = stdin; outputFile = stdout; #endif return 0; } void Cleanup(void) { #ifdef __DEBUG__ fclose(inputFile); fclose(outputFile); #endif }