首页 > 专题系列 > Java解POJ > POJ 2577 Interpreter [解题报告] Java
2013
11-11

POJ 2577 Interpreter [解题报告] Java

Interpreter

问题描述 :

A certain computer has 10 registers and 1000 words of RAM. Each register or RAM location holds a 3-digit integer between 0 and 999. Instructions are encoded as 3-digit integers and stored in RAM. The encodings are as follows:
  • 100 means halt
  • 2dn means set register d to n (between 0 and 9)
  • 3dn means add n to register d
  • 4dn means multiply register d by n
  • 5ds means set register d to the value of register s
  • 6ds means add the value of register s to register d
  • 7ds means multiply register d by the value of register s
  • 8da means set register d to the value in RAM whose address is in register a
  • 9sa means set the value in RAM whose address is in register a to the value of register s
  • 0ds means goto the location in register d unless register s contains 0

All registers initially contain 000. The initial content of the RAM is read from standard input. The first instruction to be executed is at RAM address 0. All results are reduced modulo 1000.

输入:

The input to your program consists of up to 1000 3-digit unsigned integers, representing the contents of consecutive RAM locations starting at 0. Unspecified RAM locations are initialized to 000.

输出:

The output from your program is a single integer: the number of instructions executed up to and including the halt instruction. You may assume that the program does halt.

样例输入:

299
492
495
399
492
495
399
283
279
689
078
100
000
000
000

样例输出:

16

解题代码:

//* @author  [email protected]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
 public static void main(String[] args) throws IOException {
  BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
  int[] ram=new int[1000];
  int[] reg=new int[10];
  int pos=0;
  int num=1;
  while(stdin.ready()){
   ram[pos++]=new Integer(stdin.readLine());
  }
  pos=0;
  while(ram[pos]!=100){
   switch(ram[pos]/100){
    case 0:
	if(reg[ram[pos]%10]==0){
		pos++;
	}
	else{
		pos=reg[(ram[pos]%100)/10];
	}
	break;
    case 2:
	reg[(ram[pos]%100)/10]=ram[pos]%10;
	reg[(ram[pos]%100)/10]%=1000;
	pos++;
	break;
    case 3:
	reg[(ram[pos]%100)/10]+=(ram[pos]%10);
	reg[(ram[pos]%100)/10]%=1000;
	pos++;
	break;
    case 4:
	reg[(ram[pos]%100)/10]*=(ram[pos]%10);
	reg[(ram[pos]%100)/10]%=1000;
	pos++;
	break;
    case 5:
	reg[(ram[pos]%100)/10]=reg[ram[pos]%10];
	reg[(ram[pos]%100)/10]%=1000;
	pos++;
	break;
    case 6:
	reg[(ram[pos]%100)/10]+=reg[ram[pos]%10];
	reg[(ram[pos]%100)/10]%=1000;
	pos++;
	break;
    case 7:
	reg[(ram[pos]%100)/10]*=reg[ram[pos]%10];
	reg[(ram[pos]%100)/10]%=1000;
	pos++;
	break;
    case 8:
	reg[(ram[pos]%100)/10]=ram[reg[ram[pos]%10]];
	pos++;
	break;
    case 9:
	ram[reg[ram[pos]%10]]=reg[(ram[pos]%100)/10];
	pos++;
	break;
   }
  num++;
 }
  System.out.println(num);		
 }
}