मान लीजिए कि हमारे पास एक स्ट्रिंग S है जिसमें संभावित वर्ण '0', '1' या '?' हैं। हम '?' की प्रत्येक घटना को बदलकर स्ट्रिंग टी बनाना चाहते हैं। 0 या 1 के साथ। T का असंतुलन इस प्रकार है:S में lवें और rth वर्ण के बीच 0 और 1 की घटनाओं की संख्या के बीच सभी पूर्ण अंतरों में से अधिकतम जहां 0 <=l <=r
इसलिए, यदि इनपुट S ="0??0" जैसा है, तो आउटपुट 2
. होगाइसे हल करने के लिए, हम इन चरणों का पालन करेंगे -
Define a function check(), this will take S, x,
L := 0, R = x
B := true
for initialize i := 0, when i < size of S, update (increase i by 1), do:
if S[i] is same as '0', then:
decrease L and R by 1, each
if S[i] is same as '1', then:
increase L and R by 1, each
if S[i] is same as '?', then:
if L is same as R, then:
B := false
(decrease L by 1)
(increase R by 1)
if R is same as x + 1, then:
if B is non-zero, then:
(decrease R by 1)
Otherwise
R := R - 2
if L < 0, then:
if B is non-zero, then:
(increase L by 1)
Otherwise
L := L + 2
if L > R, then:
return false
return true
From the main method, do the following
L := 1, R := 1000000
while L <= R, do:
Mid := floor of (L + R)/2
if check(S, Mid), then:
R := Mid - 1
Otherwise
L := Mid + 1
return R + 1 उदाहरण
आइए बेहतर समझ पाने के लिए निम्नलिखित कार्यान्वयन देखें -
#include <bits/stdc++.h>
using namespace std;
bool check(string S, int x) {
int L = 0, R = x;
bool B = true;
for (int i = 0; i < S.size(); i++) {
if (S[i] == '0')
L--, R--;
if (S[i] == '1')
L++, R++;
if (S[i] == '?') {
if (L == R)
B = false;
L--;
R++;
}
if (R == x + 1) {
if (B)
R--;
else
R -= 2;
}
if (L < 0) {
if (B)
L++;
else
L += 2;
}
if (L > R)
return false;
}
return true;
}
int solve(string S) {
int L = 1, R = 1000000;
while (L <= R) {
int Mid = L + R >> 1;
if (check(S, Mid))
R = Mid - 1;
else
L = Mid + 1;
}
return R + 1;
}
int main() {
string S = "0??0";
cout << solve(S) << endl;
} इनपुट
0??0
आउटपुट
2