找到可能生成的字符串 T 的可能最小不平衡度的 C++ 程序
假设我们有具有可能字符 '0'、'1'或 '?' 的字符串 S。我们想通过用 0 或 1 替换每次出现的 '?' 来生成字符串 T。T 的不平衡度为:在 S 中第 l 个和第 r 个字符之间出现的 0 和 1 的绝对差值的最大值,其中 0 <= l <= r < S 的大小。我们必须找到 T 可能的最小不平衡度。
因此,如果输入内容为 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
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP