a545中等游標、模式與固定尺寸畫面
CPE:Interpreting Control Sequences (UVa 337)
逐字解析控制序列,把寫字與游標移動明確分離。
解題思路
狀態包括十列十欄的畫面、游標列欄與插入模式旗標。普通字元在覆寫模式直接替換;插入模式要從右往左搬移同列字元,再填游標格。兩種模式寫完都只把欄位加一且截在 9,不會換列。
遇到 ^ 先讀下一個字元;若是數字,再讀一個數字當欄座標;^^ 則把 ^ 送入一般寫字程序。其他控制命令只改指定狀態,例如 ^c 清畫面卻不重設游標,^h 只回原點。N 行間換行忽略,但空白必須當文字讀進來;N=0 結束,輸出每列完整十字元及邊框。
Step-by-step animation
示意:輸入 ABC^h^iZ
步驟 1 / 3
覆寫 ABC
第一列成為 ABC 加七個空白,游標在第3欄。
A
B
C
空白×7
- 列
- 0
- 欄
- 3
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
int n, tc = 0;
string line;
while (cin >> n && n) {
getline(cin, line);
vector<string> g(10, string(10, ' '));
int r = 0, c = 0;
bool insert = false;
auto write = [&](char ch) {
if (insert)
for (int j = 9; j > c; --j)
g[r][j] = g[r][j - 1];
g[r][c] = ch;
c = min(9, c + 1);
};
for (int row = 0; row < n; ++row) {
getline(cin, line);
for (size_t i = 0; i < line.size(); ++i) {
char ch = line[i];
if (ch != '^') {
write(ch);
continue;
}
ch = line[++i];
if (ch >= '0' && ch <= '9') {
r = ch - '0';
c = line[++i] - '0';
} else if (ch == '^')
write('^');
else if (ch == 'b')
c = 0;
else if (ch == 'c')
for (auto &s : g)
s.assign(10, ' ');
else if (ch == 'd')
r = min(9, r + 1);
else if (ch == 'u')
r = max(0, r - 1);
else if (ch == 'l')
c = max(0, c - 1);
else if (ch == 'r')
c = min(9, c + 1);
else if (ch == 'e')
for (int j = c; j < 10; ++j)
g[r][j] = ' ';
else if (ch == 'h')
r = c = 0;
else if (ch == 'i')
insert = true;
else if (ch == 'o')
insert = false;
}
}
cout << "Case " << ++tc << "\n+----------+\n";
for (auto &s : g)
cout << '|' << s << "|\n";
cout << "+----------+\n";
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。