URAL 2027 2028 两个有趣的题

这两个题,讲的是有一种奇怪的语言,代码是一种二维的矩阵。

前一个题,是根据所给的要求,写一个简单的解释器。

后一个题,是用那种语言写一个简单的小程序。

挺有意思的,所以在这里纪念一下。顺便那个语言的原型是一种叫做Befunge的语言。真实存在的哟。

代码:

  简单的解释器:  

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <cctype>
#include <time.h>

using namespace std;

const int INF = 1<<30;
const int MAXN = 105;
const int MAXM = 1e5+5;
const int MAXSTEP = 1e6;
const int MAX_NUM = 1e5;
const int dir[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };

int H, W;
char G[MAXN][MAXN];
int num[MAXM], n, curNum;
int pointer[2], d;
int stepCnt;

int cur, memory[30];

bool check() {
    if (!(-MAX_NUM<=cur&&cur<=MAX_NUM)) {
    //溢出错误
        puts("OVERFLOW ERROR");
        return false;
    }
    stepCnt++;
    if (stepCnt>=MAXSTEP) {
    //超时
        puts("TIME LIMIT EXCEEDED");
        return false;
    }
    pointer[0] += dir[d][0]; pointer[1] += dir[d][1];
    if (!(0<=pointer[0]&&pointer[0]<H && 0<=pointer[1]&&pointer[1]<W)) {
    //指针越界
        puts("RUNTIME ERROR");
        return false;
    }
    if (curNum>=n) curNum = n-1;
    return true;
}

void init() {
    //初始化寄存器
    cur = 0;
    memset(memory, 0, sizeof(memory));
    //初始化指针
    pointer[0] = pointer[1] = 0;
    d = 0;
    //初始化计数器
    stepCnt = 0;
    curNum = 0;
}

void run() {
    init();
    while (true) {
        char c = G[pointer[0]][pointer[1]];
        if ('#'==c)
            break;
        else if ('^'==c)
            d = 3;
        else if ('v'==c)
            d = 1;
        else if ('<'==c)
            d = 2;
        else if ('>'==c)
            d = 0;
        else if ('@'==c)
            if (cur!=0) d = (d+1)%4;
            else d = (d+3)%4;
        else if ('A'<=c&&c<='Z')
            swap(cur, memory[c-'A']);
        else if ('?'==c) {
            cur = num[curNum++];
        } else if ('!'==c) {
            printf("%d
", cur);
            cur = 0;
        } else if ('+'==c)
            cur++;
        else if ('-'==c)
            cur--;
        else if ('.'==c)
            ;
        if (!check()) break;
    }
}

int main() {
    #ifdef Phantom01
        freopen("URAL2027.txt", "r", stdin);
    #endif //Phantom01

    while (scanf("%d%d", &H, &W)!=EOF) {
        for (int i = 0; i < H; i++)
            scanf("%s", G[i]);
        scanf("%d", &n);
        for (int i = 0; i < n; i++)
            scanf("%d", &num[i]);
        run();
    }

    return 0;
}
解释器

  小程序:

 1 9 12
 2 ?..........v
 3 >.>v>>Tv>>v.
 4 .>.>@..>@^I.
 5 .-..I..^A.-.
 6 .^..+..^+.v<
 7 .T..I..-A...
 8 .^+T<..^<...
 9 ^.........@v
10 ........#!A<
小程序
原文地址:https://www.cnblogs.com/Phantom01/p/4127073.html