C++ 程式,用於檢查異或遊戲結果為 0 或不為 0


假設我們有一個包含 N 個元素的陣列 A 和另一個二進位制字串 S。考慮兩個玩家正在玩遊戲。他們被編號為 0 和 1。有一個變數 x,其初始值為 0。遊戲有 N 輪。在第 i 輪,S[i] 執行以下其中一項操作:將 x 替換為 x XOR A[i],否則什麼都不做。第 0 號玩家希望在遊戲結束時得到 0,而第 1 號玩家希望得到非零值。我們必須檢查 x 在最後是否變為 0。

因此,如果輸入像 A = [1, 2]; S = "10",那麼輸出將為 1,因為第 1 號玩家將 x 更改為 0 XOR 1 = 1,因此無論第 0 號玩家如何選擇,它都將始終為 1。

步驟

為了解決這個問題,我們將按照以下步驟操作 -

N := size of A
Define an array judge of size: 60.
z := 0
fill judge with 0
for initialize n := N - 1, when 0 <= n, update (decrease n by 1), do:
   x := A[n]
   loop through the following unconditionally, do:
      if x is same as 0, then:
         Come out from the loop
      y := x
      I := -1
      for initialize i := 0, when i < 60, update (increase i by 1), do:
         if y mod 2 is same as 1, then:
            I := i
         y := y / 2
      if judge[I] is same as 0, then:
         judge[I] := x
         Come out from the loop
      x := x XOR judge[I]
   if S[n] is not equal to '0', then:
      if x is not equal to 0, then:
         z := 1
return z

示例

讓我們看看以下實現,以獲得更好的理解 -

#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> A, string S){
   int N = A.size();
   int judge[60];
   int z = 0;
   fill(judge, judge + 60, 0);
   for (int n = N - 1; 0 <= n; n--){
      int x = A[n];
      while (1){
         if (x == 0)
            break;
         int y = x;
         int I = -1;
         for (int i = 0; i < 60; i++){
            if (y % 2 == 1)
               I = i;
               y /= 2;
         }
         if (judge[I] == 0){
            judge[I] = x;
            break;
         }
         x ^= judge[I];
      }
      if (S[n] != '0'){
         if (x != 0)
            z = 1;
      }
   }
   return z;
}
int main(){
   vector<int> A = { 1, 2 };
   string S = "10";
   cout << solve(A, S) << endl;
}

輸入

{ 1, 2 }, "10"

輸出

1

更新時間:03-03-2022

126 次瀏覽

立即開啟您的 職業生涯

完成課程,獲得認證

開始
廣告