Saturday 21 March 2009

POJ ( acm.pku.edu.cn ) 1049

之前由于使用 char 而非 unsighed char 数据类型吃了苦头。



#include <iostream>
#include <utility>
#include <cstring>
#include <cstdio>
#include <cstdarg>
using namespace std;
#if 0
void dbg_print(char* fmt, ...){
va_list vl;
va_start(vl,fmt);
vfprintf(stderr,fmt,vl);
va_end(vl);
}
#else
#define dbg_print(...) /*nothing*/
#endif
inline unsigned char to_int(char c){
if(c>='A'){
c-=('A'-10);
} else {
c-='0';
}
return c;
}
inline unsigned char to_hex(char c){
if(c>=10){
c+='A'-10;
} else {
c+='0';
}
return c;
}
inline unsigned char to_address(char high,char low){
return (to_int(high)<<4|to_int(low));
}
void operate(char* mem){
unsigned char A=0,B=0,address,tmp;
for(char* m=mem;*m&&*m!='8';++m){
switch(*m){
case '0':
address=to_address(m[1],m[2]);
m+=2;
A=to_int(mem[address]);
dbg_print(" [debug] %c%c%c\t read A ( %01X ) from mem ( %02X )\n",*(m-2),*(m-1),*m,A,address);
break;
case '1':
address=to_address(m[1],m[2]);
m+=2;
mem[address]=to_hex(A);
dbg_print(" [debug] %c%c%c\t write A ( %01X ) to mem ( %02X )\n",*(m-2),*(m-1),*m,A,address);
break;
case '2':
tmp=A;A=B;B=tmp;
dbg_print(" [debug] %c\t\t swap A and B, got: A ( %01X ) B ( %01X )\n",*m,A,B);
break;
case '3':
tmp=A+B;
A=tmp&0xf;
B=tmp>>4;
dbg_print(" [debug] %c\t\t add A and B, got: A ( %01X ) B( %01X )\n",*m,A,B);
break;
case '4':
++A; if(A>=16) A=0;
dbg_print(" [debug] %c\t\t inc A, got: A ( %01X )\n",*m,A);
break;
case '5':
--A; if(A<0) A=0xf;
dbg_print(" [debug] %c\t\t dec A, got: A ( %01X )\n",*m,A);
break;
case '6':
address=to_address(m[1],m[2]);
m+=2;
if(A==0){
m=mem+address-1;
dbg_print(" [debug] %c%c%c\t bz, go to address %02X\n",*(m-2),*(m-1),*m,address);
break;
}
dbg_print(" [debug] %c%c%c\t bz, go on\n",*(m-2),*(m-1),*m);
break;
case '7':
address=to_address(m[1],m[2]);
m+=2;
m=mem+address-1;
dbg_print(" [debug] %c%c%c\t jump to address %02X\n",*(m-2),*(m-1),*m,address);
break;
case '8':
break;
}
}
}
void print(char* mem){
puts(mem);
}
int main() {
for(char mem[257];gets(mem);){
if(mem[0]=='8')break;
operate(mem); print(mem);
}
return 0;
}

No comments:

Post a Comment