-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem66.cpp
More file actions
75 lines (66 loc) · 1.61 KB
/
problem66.cpp
File metadata and controls
75 lines (66 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <string>
using namespace std;
class BinaryStringSortingGame {
public:
int n;
string s;
void readInput() {
cin >> n;
cin >> s;
}
void checkCodeValidity(){
for(char c : s)
if(c != '1' && c != '0'){
cout << "!! Invalid Input !!" << endl;
exit(1);
}
}
int isValidCode() {
bool misplacedOne = false;
bool misplacedZero = false;
bool foundOne = false;
for (char c : s) {
if (c == '1') foundOne = true;
else if (foundOne && c == '0') {
misplacedZero = true;
break;
}
}
bool foundZero = false;
for (int i = n - 1; i >= 0; i--) {
if (s[i] == '0') foundZero = true;
else if (foundZero && s[i] == '1') {
misplacedOne = true;
break;
}
}
return (misplacedOne && misplacedZero) ? 0 : 1;
}
int minOperations(){
int flipCount = 0;
int i = 0, j = n - 1;
while (i < j)
{
if(isValidCode()) break;
while(s[i] != '1') i++;
while(s[j] != '0') j--;
if(i < j && !isValidCode()){
swap(s[i], s[j]);
flipCount++;
}
}
return flipCount;
}
void print(int ops) {
cout << ops << endl;
}
};
int main() {
BinaryStringSortingGame bssg;
bssg.readInput();
bssg.checkCodeValidity();
int ops = bssg.minOperations();
bssg.print(ops);
return 0;
}