Count the number of times a Bulb switches its state | C ++ program for the above approach ; Function to find the number of times a bulb switches its state ; Count of 1 s ; Traverse the array ; Update count of 1 s ; Update the status of bulb ; Traverse the array Q [ ] ; Stores previous state of the bulb ; Toggle the switch and update count of 1 s ; If the bulb switches state ; Return count ; Driver Code ; Input ; Queries ; Function call to find number of times the bulb toggles
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int n , int Q [ ] , int q ) { int one = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( A [ i ] == 1 ) one ++ ; int glows = 0 , count = 0 ; if ( one >= ceil ( n / 2 ) ) glows = 1 ; for ( int i = 0 ; i < q ; i ++ ) { int prev = glows ; if ( A [ Q [ i ] - 1 ] == 1 ) one -- ; if ( A [ Q [ i ] - 1 ] == 0 ) one ++ ; A [ Q [ i ] - 1 ] ^= 1 ; if ( one >= ceil ( n / 2.0 ) ) { glows = 1 ; } else { glows = 0 ; } if ( prev != glows ) count ++ ; } return count ; } int main ( ) { int n = 3 ; int arr [ ] = { 1 , 1 , 0 } ; int q = 3 ; int Q [ ] = { 3 , 2 , 1 } ; cout << solve ( arr , n , Q , q ) ; return 0 ; }