本题是一款模拟贫吃蛇程序,游戏是在一个 $a * a$ 的网格上进行的。 其中输入第一行一个数 $a$ 。 第二行两个数 $n$ 和 $m$ 。 接下来是 $n$ 行,每行第一个数为 $opt$ ,表示操作编号。接下来的输入的变量与操作编号对应。
输出: 即第 $m$ 秒过后的地图,蛇所在的位置输出 o ,其余位置输出 .. 以换行结尾。
01 #include <bits/stdc++.h>
02 #include <windows.h>
03 using namespace std;
04 int a, mp[101][101];
05 int t[100003];
06 int y[100003];
07 int cnt;
08 int len = 2, dir = 3, die = 0;
09 const int dx[5] = {0, 0, -1, 0, 1};
10 const int dy[5] = {0, -1, 0, 1, 0};
11 int nx = 0, ny = 1;
12 int px = 1, py = 2;
13 int check(int x, int yy) {
14 if (x < 1 || x > a || yy < 1 || yy > a)
15 return 1;
16 if (cnt + 1 - mp[x][yy] < len)
17 return 1;
18 return 0;
19 }
20 void work() {
21 if (die) return;
22 px += nx;
23 py += ny;
24 die = check(px, py);
25 if (die) return;
26 mp[px][py] = ++cnt;
27 }
28 void show() {
29 for (int i = 1; i <= a; ++i) {
30 for (int j = 1; j <= a; ++j) {
31 if (mp[i][j] != 0 && mp[i][j] >= cnt - len + 1)
32 putchar('o');
33 else
34 putchar('.');
35 }
36 puts(");
37 }
38 }
39 int main() {
40 mp[1][1] = ++cnt;
41 mp[1][2] = ++cnt;
42 int n, m, op, xx;
43 char s[3];
44 scanf("%d", &a);
45 scanf("%d%d", &n, &m);
46 while (n--) {
47 scanf("%d%d", &op, &xx);
48 if (op == 1) {
49 t[xx] = 1;
50 scanf("%s", s);
51 if (s[0] == 'L')
52 y[xx] = 1;
53 else if (s[0] == 'U')
54 y[xx] = 2;
55 else if (s[0] == 'R')
56 y[xx] = 3;
57 else
58 y[xx] = 4;
59 } else {
60 t[xx] = 2;
61 }
62 }
63 for (int tm = 1; tm <= m; ++tm) {
64 if (t[tm] == 1) {
65 if (y[tm] % 2 != dir % 2) {
66 dir = y[tm];
67 nx = dx[y[tm]];
68 ny = dy[y[tm]];
69 }
70 } else if (t[tm] == 2) {
71 ++len;
72 }
73 work();
74 if (die) {
75 break;
76 }
77 }
78 show();
79 return 0;
80 }
1. B。
2. A。
3. B。
4. B。
5. A。
6. A。
这道题目代码就是在模拟这个过程,通过 $check$ 函数来判断是否死亡,如果没有死亡就一直枚举每一秒。这道题目中,用 $cnt$ 来维护时间戳,维护每个格子是在哪个时间通过的,由于速度一致,只要知道一个点的时间戳和当前长度,就可以计算出来蛇是否处于该格子。关于复杂度计算,由于我们知道如果不进行任何操作那么游戏会在 $O(x)$ 的时间内结束,共有 $n$ 次操作,所以处理复杂度为 $O(nx) = O(x^2)$