POJ 2410:Simple Computers 模拟题

来源:互联网 发布:达内java培训费用 编辑:程序博客网 时间:2024/05/29 09:15

    题目URL:http://poj.org/problem?id=2410

    这道题最初是用字符串模拟内存的一位,看了讨论版其他认的代码之后我才发现这种方式太过复杂。完全可以用一个int或者一个char来模拟一个指令。

    自己总结下,取一个字节的后5位的整数值,可以byte % 32就可以了,而取一个字节的前三位则可以byte >> 5,总结下之后发现位操作的强大之处了。于是又用位操作把这道题重新AC了一遍,用位操作之后,少了30行代码。

    字符串模拟的AC代码:

   

#include <iostream>#include <stdio.h>#include <string.h>#include <stdio.h>using namespace std;char ins[32][10];char accu[10];int pc;int getType(char *ins){return (ins[0]-'0')*4 + (ins[1]-'0')*2 + (ins[2]-'0');}int getOperand(char *ins){int res(0);for(int i(3); i<8; ++i) res = res * 2 + ins[i] - '0';return res;}int getValue(char *ins){int res(0);for(int i(0); i<8; ++i) res = res * 2 + ins[i] - '0';return res;}void dec(){for(int i(7); i>=0; --i){if(accu[i] == '1'){accu[i] = '0';break;}elseaccu[i] = '1';}}void inc(){int carry(1);for(int i(7); i>=0; --i){if(accu[i] == '1' && carry == 1) accu[i] = '0';else if(accu[i] == '0' && carry == 1) accu[i] = '1', carry = 0;else if(!carry) break;}}int main(){bool halt;while(scanf("%s", ins) != EOF){for(int i(1); i<32; ++i) scanf("%s", ins+i);halt = false;pc = 0;memset(accu, '0', sizeof(accu));while(!halt && pc < 32){switch(getType(ins[pc])){case 0:memcpy(ins[getOperand(ins[pc])], accu, sizeof(accu));pc = (pc + 1) % 32;break;case 1:memcpy(accu, ins[getOperand(ins[pc])], sizeof(accu));pc = (pc + 1) % 32;break;case 2:if(!getValue(accu)) pc = getOperand(ins[pc]);else pc = (pc + 1) % 32;break;case 3:pc = (pc + 1) % 32;break;case 4:dec();pc = (pc + 1) % 32;break;case 5:inc();pc = (pc + 1) % 32;break;case 6:pc = getOperand(ins[pc]);break;case 7:halt = true;break;}}for(int i(0); i<8; ++i) printf("%c", accu[i]);printf("\n");}system("pause");return 0;}

    用char类型模拟的AC代码:

   

#include <iostream>#include <stdio.h>using namespace std;unsigned char ins[32], accu, pc;char str[10];unsigned char getValue(char *ins){unsigned char res(0);for(int i(0); i<8; ++i) res = res * 2 + ins[i] - '0';return res;}int main(){bool halt;int type, value;while(scanf("%s", str) != EOF){ins[0] = getValue(str);for(int i(1); i<32; ++i) scanf("%s", str), ins[i] = getValue(str);halt = false;pc = accu = 0;while(!halt){type = ins[pc] >> 5;value = ins[pc] % 32;switch(type){case 0:ins[value] = accu;pc = (pc + 1) % 32;break;case 1:accu = ins[value];pc = (pc + 1) % 32;break;case 2:if(!accu) pc = value;else pc = (pc + 1) % 32;break;case 3:pc = (pc + 1) % 32;break;case 4:--accu;pc = (pc + 1) % 32;break;case 5:++accu;pc = (pc + 1) % 32;break;case 6:pc = ins[pc] % 32;break;case 7:halt = true;break;}}for(int i(7); i>=0; --i)printf("%d", (accu >> i) & 1);printf("\n");}system("pause");return 0;}



原创粉丝点击