여기서 우리는 한 가지 문제를 보게 될 것입니다. 하나의 이진 배열이 있습니다. n개의 요소가 있습니다. 각 요소는 0 또는 1입니다. 처음에는 모든 요소가 0입니다. 이제 M 명령을 제공합니다. 각 명령에는 시작 및 종료 인덱스가 포함됩니다. 따라서 command(a, b)는 위치의 요소에서 위치 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