UVA-10033 Interpreter

题目:

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=974

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// oj.cpp : 定义控制台应用程序的入口点。
//

#include <iostream>
#include <limits>
#include <algorithm>
#include <numeric>
#include <string>
#include <utility>
#include <cstdlib>
#include <vector>
#include <sstream>
//#include <cstdio>

using namespace std;

int reg[1000];
string ram[1000];

inline void set_to(int& a, const int& b)
{
a = b;
a %= 1000;
}

inline string to_str(int a)
{
ostringstream sout;
sout << a;
return sout.str();
}

inline int to_int(string S)
{
istringstream s(S);
int a;
s >> a;
return a;
}

int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);

int T;
cin >> T;
string L;
getline(cin, L);
getline(cin, L);

while (T--)
{
fill(reg, reg + 1000, 0);
fill(ram, ram + 1000, "");

int i = 0;
while (getline(cin, L) && L != "")
ram[i++] = L;

i = 0;
int cnt = 0;
bool is_on = true;
while (is_on)
{
++cnt;
L = ram[i];

switch (L[0]-'0')
{
case 1:
is_on = false;
break;
case 2:
set_to(reg[L[1] - '0'], L[2] - '0');
break;
case 3:
set_to(reg[L[1] - '0'], reg[L[1] - '0'] + L[2] - '0');
break;
case 4:
set_to(reg[L[1] - '0'], reg[L[1] - '0'] * (L[2] - '0'));
break;
case 5:
set_to(reg[L[1] - '0'], reg[L[2] - '0']);
break;
case 6:
set_to(reg[L[1] - '0'], reg[L[1] - '0'] + reg[L[2] - '0']);
break;
case 7:
set_to(reg[L[1] - '0'], reg[L[1] - '0'] * (reg[L[2] - '0']));
break;
case 8:
set_to(reg[L[1] - '0'], to_int(ram[reg[L[2] - '0']]));
break;
case 9:
ram[reg[L[2] - '0']] = to_str(reg[L[1] - '0']);
break;
case 0:
if (reg[L[2] - '0'])
i = reg[L[1] - '0'] - 1;
break;
}
++i;
}
cout << cnt << endl;
if (T)
cout << endl;
}
}

解析&吐槽:

要你模拟一台计算机。计算机的指令(程序语句)存储在 RAM 中,从标准输入读入,按顺序执行。 如果遇到 0 打头的语句,就跳到相应的 RAM 的语句来执行。RAM 为 1000 单位大小, 还有一个 10 单位大小的寄存器,每个单位能存储 0-999 的数字。超过 999 的数字会溢出,只保留 低位。输出执行的语句的数量。

然后模拟就好了_(:зゝ∠)_

本作品采用 署名-相同方式共享 4.0 国际 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 “不科学的科学君” (Liu233w) 与博客链接: https://liu233w.github.io ,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

加载评论框需要翻墙