题目链接
我们将所有为0的位置的下标存起来。 然后我们枚举左端点i, 那么i+k就是右端点。 然后我们三分John的位置, 找到下标为i时的最小值。
复杂度 $ O(nlogn) $
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
const int maxn = 1e5+5;
int a[maxn], k;
int cal(int x, int pos) {
return max(abs(a[x]-a[pos]), abs(a[pos+k]-a[x]));
}
int main()
{
int n, cnt = 0;
string s;
cin>>n>>k;
cin>>s;
for(int i = 0; i<n; i++) {
if(s[i] == '0')
a[cnt++] = i;
}
int ans = inf;
for(int i = 0; i < cnt - k; i++) {
int l = i, r = i + k;
while(l < r) {
int lmid = (l*2+r)/3;
int rmid = (l+r*2+2)/3;
if(cal(lmid, i) > cal(rmid, i)) {
l = lmid + 1;
} else {
r = rmid - 1;
}
}
ans = min(ans, cal(l, i));
}
cout<<ans<<endl;
return 0;
}