In an attempt to escape the Mischievous Mess Makers’ antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.
Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.
Input
The first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John.The second line contains a string of length n describing the rooms. The i-th character of the string will be ‘0’ if the i-th room is free, and ‘1’ if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are ‘0’, so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.
Output
Print the minimum possible distance between Farmer John’s room and his farthest cow.Examples
input
7 2
0100100
output
2
input
5 1
01010
output
2
input
3 2
000
output
1Note
In the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.
In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.
#include<bits/stdc++.h>
using namespace std;int mmap[100010];
int main()
{
int n,p;
cin>>n>>p;
string s;
cin>>s;
int l=0,r=n-1,k=1,mmin=0x3f3f3f3f,x=0,y=0,visit[100010];
for(int i=0;i<n;i++)
if(s[i]=='0')
mmap[k++]=i;//记录第k个0的位置i
int mm=100005,ans;
for(int j=1;j+p<k&&mmap[j+p]<n;j++){
x=mmap[j];y=mmap[j+p];
l=x;r=y;
int mid=(l+r)/2;
if(s[mid]=='0')
ans=max(mid-x,y-mid);
else{
int t=lower_bound(mmap,mmap+k,mid)-mmap;//二分
ans=max(mmap[t]-x,y-mmap[t]);
int i=t-1;
while(i>=j&&ans>max(mmap[i]-x,y-mmap[i])){
ans=max(mmap[i]-x,y-mmap[i]);
i--;
}
i=t+1;
while(i<=j+p&&ans>max(mmap[i]-x,y-mmap[i])){
ans=max(mmap[i]-x,y-mmap[i]);
i++;
}
}
if(mm>ans)
mm=ans;
}
cout<<mm<<endl;
return 0;
}

为确保牛群安全,农场主约翰需在一行排列的空房间中选择k+1间相邻的房间作为自己与牛的住处,并尽可能缩小与最远牛之间的距离。此问题探讨了如何通过算法计算最小可能的距离。
603

被折叠的 条评论
为什么被折叠?



