Skip to content

Commit 5c8e121

Browse files
authored
Merge pull request #16 from deepikabirthare/master
updated the code for Lightupbulbs.cpp in adhoc problems folder. Reduced code size and added comments for new code
2 parents 17c7e0c + 78c3ccd commit 5c8e121

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

adhoc problems/Lightupbulbs.cpp

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
66
*/
77

8-
98
/*
109
PROBLEM STATEMENT
1110
A bulb can be ‘ON’ or ‘OFF’. Mr. Navdeep got ‘n’ number of bulbs and their status, whether they are ‘ON’ or ‘OFF’. Their status is represented in a string of size ‘n’ consisting of 0’s and 1’s, where ‘0’ represents the bulb is in ‘OFF’ condition and ‘1’ represent the bulb is ‘ON’. Mr. Navdeep has been given the task to light up all the bulbs.
@@ -32,7 +31,7 @@ First, Reverse substring (0, 1): “01000” -> “10000”, COST = 1
3231
Second, Invert substring (1, 4): “10000” -> “11111”, COST = 10
3332
Total cost = 1+10 => 11
3433
*/
35-
34+
/*
3635
#include <bits/stdc++.h>
3736
3837
using namespace std;
@@ -91,4 +90,40 @@ int main( int argc , char ** argv )
9190
9291
9392
}
93+
*/
9494

95+
#include <bits/stdc++.h>
96+
97+
using namespace std;
98+
int main()
99+
{
100+
long long n, x, y, num = 0;
101+
//num = no. of reverse operations required to put all the zeros together so that only one light up operation is required
102+
cin >> n >> x >> y;
103+
string s;
104+
cin >> s;
105+
s = s + '1';
106+
//no. of reverse operations required = no. of continuos segments of zeros - 1
107+
//that's why I added 1 at the end of string to count no. of changes from zero to one
108+
//example : s = 0011100010 in this case num= 3 -1 = 2
109+
for (int i = 1; i < n + 1; i++)
110+
{
111+
if (s[i] == '1')
112+
{
113+
if (s[i - 1] == '0')
114+
{
115+
num++;
116+
}
117+
}
118+
}
119+
if (num == 0)
120+
{
121+
cout << "0";
122+
return 0;
123+
}
124+
long long ans = min(num * y, (num - 1) * x + y);
125+
//num*y = cost of lighting all the segments of zeros in our example it will be 3*y as there are 3 segments of zeros
126+
//(num-1)*x = cost of reverse operations required to get one continuos segment + 1*y (cost of lighting up that 1 segment)
127+
cout << ans;
128+
return 0;
129+
}

0 commit comments

Comments
 (0)