Algorithm 版 (精华区)
发信人: pamws (书虫), 信区: Algorithm
标 题: 1098K-Simple Computers-ZJU
发信站: 哈工大紫丁香 (2002年10月09日17:24:05 星期三), 站内信件
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <fcntl.h>
#define ONLINE_JUDGE 1
char mem[32][8];
int accu=0;
int pc=0;
char * dec2bin(int num, int dig)
{
char * res=new char[dig+1];
for (int i=0; i<dig; i++) {
if (num>=(int)pow(2, dig-i-1)) {
num-=(int)pow(2, dig-i-1);
res[i]='1';
} else {
res[i]='0';
}
}
res[dig]=0;
return res;
}
int bin2dec(char * num, int dig)
{
int res=0;
for (int i=0; i<dig; i++) {
if (num[i]=='1') {
res+=(int)pow(2, dig-i-1);
}
}
return res;
}
int main(void)
{
#ifndef ONLINE_JUDGE
freopen("1098.in", "r", stdin);
freopen("1098.out", "w", stdout);
#endif
int i, j;
while (true) {
halt:
memset(mem, '0', 32*8);
accu=0;
pc=0;
char buff[9];
for (i=0; i<32; i++) {
if (scanf("%s", buff)==EOF) {
return 0;
} else {
for (j=0; j<8; j++) {
mem[i][j]=(buff[j]=='0')?'0':'1';
}
}
}
while (true) {
char INS[4]; strncpy(INS, mem[pc], 3); INS[3]=0;
char ADD[6]; strncpy(ADD, mem[pc]+3, 5); ADD[5]=0;
pc+=1; if (pc>31) pc=0;
int addr=bin2dec(ADD, 5);
switch (bin2dec(INS, 3)) {
case 0: //STA x store the value of the accu into memory byte x
strncpy(mem[addr], dec2bin(accu, 8), 8);
break;
case 1: //LDA x load the value of memory byte x into the accu
accu=bin2dec(mem[addr], 8);
break;
case 2: //BEQ x if the value of the accu is 0 load the value x
into the pc
if (accu==0) {
pc=bin2dec(ADD, 5);
}
break;
case 3: //NOP no operation
break;
case 4: //DEC subtract 1 from the accu
accu-=1;
if (accu<0) accu=255;
break;
case 5: //INC add 1 to the accu
accu+=1;
if (accu>255) accu=0;
break;
case 6: //JMP x load the value x into the pc
pc=bin2dec(ADD, 5);
break;
case 7: //HLT terminate program
printf("%s\n", dec2bin(accu, 8));
goto halt;
break;
}
}
}
return 0;
}
--
I Love Google...
※ 来源:·哈工大紫丁香 bbs.hit.edu.cn·[FROM: 202.118.226.228]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:8.387毫秒