a797中等跨機器人共享的格點氣味
CPE:Mutant Flatworld Explorers (UVa 118)
正確處理轉向、越界忽略與消失停止。
解題思路
以 N,E,S,W 的索引 0,1,2,3 表示方向,L 與 R 分別減一、加一取模。F 先算候選座標,若在範圍內就移動;若越界且目前格點有氣味,整條 F 被忽略,位置與朝向都不變。
越界而無氣味時,在目前格點留下氣味、標記 LOST 並停止該機器人的後續指令。氣味集合跨機器人保存,且只記座標,不記朝向。世界範圍含 0 與右上角兩端,所以只有小於 0 或大於上限才算越界。每個機器人的指令用整行讀取,也能接受空指令列;輸入直到 EOF,每個機器人用一行印出最終狀態。
Step-by-step animation
示意:世界 (1,1),兩台從 (0,1) 朝北
步驟 1 / 3
第一台前進
候選 (0,2) 越界,(0,1) 原本無氣味。
(0,1)
(0,2) 越界
- 氣味數
- 0
#include <iostream>
#include <string>
#include <set>
#include <utility>
using namespace std;
int main() {
int xmax, ymax;
if (!(cin >> xmax >> ymax))
return 0;
set<pair<int, int>> scent;
string dirs = "NESW", commands;
char face;
int x, y;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
string rest;
while (cin >> x >> y >> face) {
getline(cin, rest);
getline(cin, commands);
int d = int(dirs.find(face));
bool lost = false;
for (char cmd : commands) {
if (cmd == 'L')
d = (d + 3) % 4;
else if (cmd == 'R')
d = (d + 1) % 4;
else if (cmd == 'F') {
int nx = x + dx[d], ny = y + dy[d];
if (nx < 0 || nx > xmax || ny < 0 || ny > ymax) {
if (scent.count({x, y}))
continue;
scent.insert({x, y});
lost = true;
break;
}
x = nx;
y = ny;
}
}
cout << x << ' ' << y << ' ' << dirs[d] << (lost ? " LOST" : "") << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。