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
| #include <iostream> #include <set> #include <string> #include <vector> #include <cassert>
using namespace std;
int getNext(set<pair<int, int>> &visited, const int x, int direction) { auto it = visited.lower_bound({x + 1, x + 1}); assert(it != visited.begin()); --it; if (direction > 0) return it->second; else return it->first - 1; }
void visitRow(set<pair<int, int>> &row, int y) { auto it = row.lower_bound({y + 1, y + 1}); if (it == row.begin()) { it = row.insert({y, y + 1}).first; } else { --it; if (it->first <= y && it->second > y) { return; } else if (it->second == y) { auto old = it; it = row.insert(it, {it->first, it->second + 1}); it = row.erase(old); } else { it = row.insert({y, y + 1}).first; } } if (next(it) != row.end() && next(it)->first == it->second) { int end = next(it)->second; int begin = it->first; row.erase(next(it)); row.erase(it); row.insert({begin, end}); } }
void visit(vector<set<pair<int, int>>> &visitedR, vector<set<pair<int, int>>> &visitedC, const int x, int y) { auto &row = visitedR[x]; visitRow(row, y); auto &column = visitedC[y]; visitRow(column, x); }
pair<int, int> solve(const string &instructions, const int R, const int C, const int Sr, const int Sc) { int current_x = Sr, current_y = Sc; vector<set<pair<int, int>>> visitedR(R + 1); vector<set<pair<int, int>>> visitedC(C + 1); visit(visitedR, visitedC, current_x, current_y); for (char c : instructions) { switch (c) { case 'N': current_x = getNext(visitedC[current_y], current_x, -1); break; case 'E': current_y = getNext(visitedR[current_x], current_y, 1); break; case 'W': current_y = getNext(visitedR[current_x], current_y, -1); break; case 'S': current_x = getNext(visitedC[current_y], current_x, 1); break; default: cerr << "Bad instruction: " << c << endl; break; } visit(visitedR, visitedC, current_x, current_y); } return {current_x, current_y}; }
int main() { int T; cin >> T; for (int i = 0; i < T; ++i) { int N, R, C, Sr, Sc; cin >> N >> R >> C >> Sr >> Sc; string instructions; cin >> instructions; auto ans = solve(instructions, R, C, Sr, Sc); cout << "Case #" << i + 1 << ": " << ans.first << " " << ans.second << endl; } return 0; }
|