a864簡單

113 嘉義資訊程式競賽|XOR 數字

避免更新污染相鄰計算。

解題思路

每個輸出b[i]只依賴原始a[(i−1+N)%N]與a[(i+1)%N],用模數索引連接環首尾。

保留原陣列,將結果放另一陣列或直接逐項輸出。不能覆寫a,因為後面的結果仍需要原始相鄰位元。

XOR的真值是不同為1、相同為0;即使N很小、兩個鄰位指向同一元素,該元素XOR自己仍為0。

O(N)時間、O(N)空間;Python輸入詞O(N)。

Step-by-step animation

示例:第一位鄰居是尾端0與第二位0。

回報動畫錯誤
步驟 1 / 3

環1,0,0

第一位鄰居是尾端0與第二位0。

1
0
0
b1
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int &x : a)
        cin >> x;
    for (int i = 0; i < n; i++) {
        if (i)
            cout << ' ';
        cout << (a[(i + n - 1) % n] ^ a[(i + 1) % n]);
    }
    cout << '\n';
}

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

更多