Chinaunix首页 | 论坛 | 博客
  • 博客访问: 71861
  • 博文数量: 41
  • 博客积分: 1475
  • 博客等级: 上尉
  • 技术积分: 440
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-27 22:49
文章分类
文章存档

2012年(8)

2011年(1)

2009年(32)

我的朋友
最近访客

分类:

2009-06-03 19:46:56

题目:
 
解题思路: 简单题,模拟即可。
 
代码:
 

/*
 *******************************************************************************
 *
 * Filename: 10033.cpp
 *
 * Description:
 *
 * Author: Ye Xiaofeng , yexf@xa.nec-as.nec.com.cn
 *
 *******************************************************************************
 */


#include <iostream>

using namespace std;


class Computer {
public:
    Computer(int *mem)
    {
        memcpy(this->mem, mem, 1000*sizeof(int));
        memset(reg, 0, 10*sizeof(int));
        ip = 0;
        cmdCount = 0;
    }
    int excute();
    void excuteCmd(int cmd);
private:
    int ip; // cur instruction address

    int reg[10];
    int mem[1000];
    int cmdCount;
};

void Computer::excuteCmd(int cmd)
{
    int cmdType = cmd / 100;
    int p1 = (cmd % 100) / 10;
    int p2 = (cmd % 100) % 10;

    ip++;
    switch (cmdType) {
    case 0:
        if (reg[p2] != 0) {
            ip = reg[p1];
        }
        break;
    case 2:
        reg[p1] = p2;
        break;
    case 3:
        reg[p1] += p2;
        reg[p1] %= 1000;
        break;
    case 4:
        reg[p1] *= p2;
        reg[p1] %= 1000;
        break;
    case 5:
        reg[p1] = reg[p2];
        break;
    case 6:
        reg[p1] += reg[p2];
        reg[p1] %= 1000;
        break;
    case 7:
        reg[p1] *= reg[p2];
        reg[p1] %= 1000;
        break;
    case 8:
        reg[p1] = mem[reg[p2]];
        break;
    case 9:
        mem[reg[p2]] = reg[p1];
        break;
    }
}

//
// exucte code.
// Return: the number of instructions executed
//
int Computer::excute()
{
    int cmd = mem[ip];
    while (1) {
        cmdCount++;
        if (100 == cmd) {
            // halt
            break;
        }
        excuteCmd(cmd);
        cmd = mem[ip];
        if (ip >= 1000) {
            break;
        }
    }

    return cmdCount;
}

int main()
{
    int mem[1000];
    int caseNum = 0;
    char buffer[4];

    cin >> caseNum;
    cin.getline(buffer, 4);
    cin.getline(buffer, 4);
    for (; caseNum != 0; caseNum--) {
        memset(mem, 0, 1000*sizeof(int));
        int memPos = 0;
        cin.getline(buffer, 4);
        while (buffer[0] != '\0') {
            mem[memPos] = atoi(buffer);
            memPos++;
            cin.getline(buffer, 4);
        }

        Computer com(mem);
        cout << com.excute() << endl;
        if (caseNum != 1) {
            cout << endl;
        }
    }
}

阅读(789) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~