a573簡單雙緩衝的同步格點更新

CPE:Rock, Scissors, Paper (UVa 10443)

所有勝負都讀取同一天的舊地圖。

前往題目練習 →回報教學錯誤時間 O(天數×列數×欄數),空間 O(列數×欄數)。

解題思路

每個物種只有一種天敵:R怕P、P怕S、S怕R。檢查一格的四個舊鄰居,只要有天敵,下一天就改成天敵,否則保持原物種。不需比較鄰居多寡,因為所有能打敗它的鄰居都是同一物種。

每一天建立新地圖next,全部格子都以old讀取,完成後才交換。若直接在old逐格修改,早先變化會影響後面格子的判斷,變成錯誤的連鎖更新。做滿指定天數,n=0時原圖直接輸出;兩組地圖之間留一空行。

Step-by-step animation

示意:一列 RSP,模擬兩天

回報動畫錯誤
步驟 1 / 3

第0天

R剋S,S剋P,但尚未更新。

R
S
P
天數
0

Reference solution

回報程式錯誤

完整程式

#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 t;
    cin >> t;
    for (int tc = 0; tc < t; ++tc) {
        int r, c, days;
        cin >> r >> c >> days;
        vector<string> g(r);
        for (auto &s : g)
            cin >> s;
        while (days--) {
            auto next = g;
            for (int i = 0; i < r; ++i)
                for (int j = 0; j < c; ++j) {
                    char enemy = g[i][j] == 'R' ? 'P' : g[i][j] == 'P' ? 'S' : 'R';
                    for (auto [di, dj] : vector<pair<int, int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) {
                        int x = i + di, y = j + dj;
                        if (x >= 0 && x < r && y >= 0 && y < c && g[x][y] == enemy)
                            next[i][j] = enemy;
                    }
                }
            g.swap(next);
        }
        if (tc)
            cout << '\n';
        for (auto &s : g)
            cout << s << '\n';
    }
}

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

更多