a701簡單不可變狀態快照與循環偵測

CPE:Ducci Sequence (UVa 1594)

每步同時更新相鄰差,辨認全零或重複數組。

前往題目練習 →回報教學錯誤S≤1000步,Python雜湊平均 O(Sn) 時間與 O(Sn) 空間;C++有序集合上界 O(Sn log S)。

解題思路

新狀態第i格是abs(old[i]−old[(i+1)%n]),最後一格也要接回第一格。所有新值都必須從同一份舊數組計算,因此建立另一個陣列,算完後整體替換;原地逐格修改會把新舊狀態混用。

每輪先檢查是否全零,是就輸出ZERO;否則查完整狀態是否已出現,若重複表示確定性轉換進入週期,輸出LOOP。把狀態加入集合再轉換。各值保持在有限範圍,且本地保證1000步內停止,保存狀態即可,不需要猜固定迭代次數。每組重建集合,依開頭T處理。

Step-by-step animation

示意:n=3,初始 1,2,3

回報動畫錯誤
步驟 1 / 3

第一步

|1−2|、|2−3|、|3−1|得到1,1,2。

1
1
2
步
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main() {
    int tests;
    cin >> tests;
    while (tests--) {
        int n;
        cin >> n;
        vector<int> a(n);
        for (int &x : a)
            cin >> x;
        set<vector<int>> seen;
        while (true) {
            if (all_of(a.begin(), a.end(), [](int x) { return x == 0; })) {
                cout << "ZERO\n";
                break;
            }
            if (!seen.insert(a).second) {
                cout << "LOOP\n";
                break;
            }
            vector<int> b(n);
            for (int i = 0; i < n; i++)
                b[i] = abs(a[i] - a[(i + 1) % n]);
            a.swap(b);
        }
    }
}

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

更多