a805困難原始儲存格座標逐指令追蹤

CPE:Spreadsheet Tracking (UVa 512)

正確處理同批插刪的共同參照座標。

前往題目練習 →回報教學錯誤Q 個查詢、K 道操作、每道最多 A 個編號;時間 O(QKA),保存操作 O(KA)。

解題思路

先保存操作,再對每個查詢的原始座標獨立重播。交換 EX 若碰到追蹤位置就換到另一端;刪除列或欄若直接刪到追蹤座標便標記 GONE,否則減去嚴格小於目前編號的刪除數。資料一旦刪除便不會被後續插入復原。

插入是在指定編號之前,因此追蹤座標要加上小於或等於目前編號的插入數。對同一道指令,先用舊座標算完全部影響才一次更新,不能邊處理清單邊移動,否則會把同批編號錯當成更新後座標。重播和真正移動表格等價,但只需維護兩個整數。試算表間留一個空白行,標頭與座標標點依題目格式。

Step-by-step animation

示意:追蹤 (4,3),IR 2 2 4,再 DC 1 1,再 EX 6 2 1 1

回報動畫錯誤
步驟 1 / 3

插入列

原列 4 之前插入在 2、4 的兩列,列號變成 6。

(4,3)
+2 列
(6,3)
r
6
c
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct Operation {
    string kind;
    vector<int> a;
};
int main() {
    int rows, cols, tc = 0;
    while (cin >> rows >> cols && (rows || cols)) {
        int n;
        cin >> n;
        vector<Operation> ops(n);
        for (auto &op : ops) {
            cin >> op.kind;
            int count = 4;
            if (op.kind != "EX")
                cin >> count;
            op.a.resize(count);
            for (int &x : op.a)
                cin >> x;
        }
        if (tc)
            cout << '\n';
        cout << "Spreadsheet #" << ++tc << '\n';
        int q;
        cin >> q;
        while (q--) {
            int r, c;
            cin >> r >> c;
            int x = r, y = c;
            bool gone = false;
            for (auto &op : ops) {
                auto &a = op.a;
                if (op.kind == "EX") {
                    if (x == a[0] && y == a[1]) {
                        x = a[2];
                        y = a[3];
                    } else if (x == a[2] && y == a[3]) {
                        x = a[0];
                        y = a[1];
                    }
                } else {
                    int &v = op.kind[1] == 'R' ? x : y;
                    bool erase = op.kind[0] == 'D';
                    if (erase && find(a.begin(), a.end(), v) != a.end()) {
                        gone = true;
                        break;
                    }
                    int shift = 0;
                    for (int p : a)
                        if (erase ? p < v : p <= v)
                            ++shift;
                    v += erase ? -shift : shift;
                }
            }
            cout << "Cell data in (" << r << ',' << c << ") ";
            if (gone)
                cout << "GONE\n";
            else
                cout << "moved to (" << x << ',' << y << ")\n";
        }
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多