 SIMPLE

# PROBLEM:

You are standing in front of a hallway with N consecutive doors. You want to cross through the N doors.

You may only walk through open doors. You also have a magic wand, that can flip the state of all doors. Determine the minimum number of times you need to use the wand.

# EXPLANATION:

The solution is rather straightforward.

If the door we have to cross is open, simply walk through it (it makes no sense to use the wand and close the door) and if the door is closed, use the wand, flipping the status of all doors, and then walk through the door.

All that remains is to implement the above idea efficiently. Everytime we use the wand, it is inefficient to manually flip the status of all doors.

Rather, if we have used the wand k times thus far, the status of any door is equal to its initial state if k is even, and is flipped otherwise (the proof of which is trivial and left to the reader as an exercise).

Therefore, we iterate through the doors from left to right, and in each step, check if the door is open or closed (with the above trick) and use the wand appropriately.

# TIME COMPLEXITY:

Since we iterate through the N doors once, the total time complexity is

O(N)

per test case.

# SOLUTIONS:

Editorialist’s solution can be found here.
Author’s solution can be found here.

Experimental: For evaluation purposes, please rate the editorial (1 being poor and 5 excellent)

• 1
• 2
• 3
• 4
• 5

0 voters

#include<bits/stdc++.h>
#include
using namespace std;
#define ll long long
int main()
{
int t;
cin>>t;
while(t–)
{
int ans=0;
string s;
cin>>s;
for(int i=0;i<s.length();i++)
{
if(i==0 && s[i]==‘1’)
continue;
else if(s[i]==‘0’ && s[i]!=s[i-1]|| s[i]==‘1’ && s[i]!=s[i-1])
ans++;

``````  }
cout<<ans<<endl;
}
``````

}
//is this code fine