题解:P15539 [CCC 2026 J4] Snail Path
这题是非常好的题,适合用来巩固 STL 的运用。
我们使用一个 map 来记录有没有访问过这个格子,然后按照题意模拟。切记一个一个格子走。如果当前这个格子没访问过,就标记一下;如果访问过了,就给答案加一。最后输出答案即可。
设每次移动的最大距离为 \(k\),时间复杂度为 \(\Theta(km\log km)\),非常足够。
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef pair <int, int> PII;
int m;
map <PII, bool> mp;
int main() {
cin >> m;
int ans = 0;
int x = 0, y = 0;
mp[{x, y}] = true;
for (int i = 1; i <= m; i++) {
string s;
cin >> s;
int t;
if (s.size() == 2) {
t = s[1] - '0';
}
else {
t = (s[1] - '0') * 10 + (s[2] - '0');
}
for (int j = 1; j <= t; j++) {
if (s[0] == 'N') {
y++;
}
else if (s[0] == 'S') {
y--;
}
else if (s[0] == 'E') {
x++;
}
else {
x--;
}
if (mp[{x, y}] == true) {
ans++;
}
mp[{x, y}] = true;
}
}
cout << ans << endl;
return 0;
}

浙公网安备 33010602011771号