生成された文字列Tの可能な限り最小のアンランスを見つけるためのC++プログラム
可能な文字が「0」、「1」、または「?」の文字列Sがあるとします。 '?'の各出現を置き換えることによって文字列Tを作成したいと思います。 Tの不均衡は次のようになります。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
-
LCMを見つけるためのC++プログラム
2つの数値の最小公倍数(LCM)は、両方の倍数である最小公倍数です。 例:15と9の2つの数字があるとします。 15 = 5 * 3 9 = 3 * 3 したがって、15と9のLCMは45です。 2つの数値のLCMを見つけるプログラムは次のとおりです- 例 #include <iostream> using namespace std; int main() { int a=7, b=5, lcm; if(a>b) lcm = a; else  
-
GCDを見つけるためのC++プログラム
2つの数値の最大公約数(GCD)は、両方を除算する最大の数値です。 例:45と27の2つの数字があるとします。 45 = 5 * 3 * 3 27 = 3 * 3 * 3 したがって、45と27のGCDは9です。 2つの数値のGCDを見つけるプログラムは次のとおりです。 例 #include <iostream> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int