สมมติว่าเรามีอาร์เรย์ A ที่มีองค์ประกอบ n และรายการข้อความค้นหา Q ที่มีข้อความค้นหา q อีกรายการ eachQuery[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,