ที่นี่เราจะเห็นปัญหาหนึ่ง เรามีอาร์เรย์ไบนารีหนึ่งอัน มี n องค์ประกอบ แต่ละองค์ประกอบจะเป็น 0 หรือ 1 ในขั้นต้น องค์ประกอบทั้งหมดจะเป็น 0 ตอนนี้ เราจะจัดเตรียมคำสั่ง M แต่ละคำสั่งจะมีดัชนีเริ่มต้นและสิ้นสุด ดังนั้นคำสั่ง (a, b) แสดงว่าคำสั่งจะถูกใช้จากองค์ประกอบที่ตำแหน่ง a ไปยังองค์ประกอบที่ตำแหน่ง b คำสั่งจะสลับค่า ดังนั้นมันจะสลับจากดัชนี ath เป็นดัชนี bth ปัญหานี้ง่าย ตรวจสอบอัลกอริทึมเพื่อให้ได้แนวคิด
อัลกอริทึม
toggleCommand(arr, a, b)
Begin for each element e from index a to b, do toggle the e and place into arr at its position. done End
ตัวอย่าง
#include <iostream>
using namespace std;
void toggleCommand(int arr[], int a, int b){
for(int i = a; i <= b; i++){
arr[i] ^= 1; //toggle each bit in range a to b
}
}
void display(int arr[], int n){
for(int i = 0; i<n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int n = sizeof(arr)/sizeof(arr[0]);
display(arr, n);
toggleCommand(arr, 3, 6);
toggleCommand(arr, 8, 10);
toggleCommand(arr, 2, 7);
display(arr, n);
} ผลลัพธ์
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 0