C++ 程式碼處理二進位制陣列中的查詢操作
假設我們有一個包含 n 個元素的陣列 A 和另一個包含 q 個查詢的查詢列表 Q。每個 Query[i] 包含一對 (x, k)。當我們處理查詢時,對於 x:將 A[x] 的值減 1。對於 k,列印第 k 個最大元素。最初,A 中的所有元素都為 0 或 1。
因此,如果輸入像 A = [1, 1, 0, 1, 0];Q = [[2, 3], [1, 2], [2, 3], [2, 1], [2, 5]],則輸出將為 [1, 1, 1, 0]
步驟
為了解決這個問題,我們將遵循以下步驟 −
n := size of A m := 0 for initialize i := 0, when i < n, update (increase i by 1), do: if A[i] is non-zero, then: (increase m by 1) for initialize j := 0, when j < size of Q, update (increase j by 1), do: x := Q[j, 0] k := Q[j, 1] if x is same as 0, then: if A[k] is non-zero, then: (decrease m by 1) Otherwise (increase m by 1) A[k] := A[k] XOR 1 Otherwise if m >= k, then: print 1 Otherwise print 0
示例
讓我們看看以下實現以更好地理解 −
#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A, vector<vector<int>> Q){
int n = A.size();
int m = 0;
for (int i = 0; i < n; i++){
if (A[i])
m++;
}
for (int j = 0; j < Q.size(); j++){
int x = Q[j][0];
int k = Q[j][1];
if (x == 0){
if (A[k])
m--;
else
m++;
A[k] ^= 1;
}
else{
if (m >= k)
cout << 1 << ", ";
else
cout << 0 << ", ";
}
}
}
int main(){
vector<int> A = { 1, 1, 0, 1, 0 };
vector<vector<int>> Q = { { 1, 2 }, { 0, 1 }, { 1, 2 }, { 1, 0 },{ 1, 4 } };
solve(A, Q);
}輸入
{ 1, 1, 0, 1, 0 }, { { 1, 2 }, { 0, 1 }, { 1, 2 }, { 1, 0 }, { 1, 4 }}輸出
1, 1, 1, 0,
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP