CROC 2016 - Elimination Round Enduring Exodus
这道题的意思是给你一串01序列, 0代表空房子, 1代表非空的房子, 农夫约翰和他的K个牛要住进空房子里面,i房子和j房子的距离是|j-i| 问农夫约翰和他的最远的牛的最小值是多少? 我们可以枚举牛的起点, 算出终点然后二分农夫约翰的位置, 代码如下:
#include <bits/stdc++.h> using namespace std; int a[100000 + 100], na; int Binary(int num) { //找出<=num的最后一个位置 int l=0, h = na-1; int res = -1; while(l <= h) { int mid = (l+h)/2; if(a[mid] <= num) { res = mid; l = mid + 1; } else h = mid-1; } return res; } int main(){ int n, k; scanf("%d%d", &n, &k); na = 0; for(int i=0; i<n; i++) { int t; scanf("%1d", &t); if(t==0) a[na++] = i; } k+=1; int res = 0x3f3f3f3f; for(int i=0; i+k-1<=na-1; i++) { int lnum = a[i], hnum = a[i+k-1]; int pos = Binary((lnum+hnum)/2); int tp1 = max(abs(a[i]-a[pos]), abs(a[i+k-1]-a[pos])); int tp2 = 0x3f3f3f3f; if(pos+1<na) tp2 = max(abs(a[i]-a[pos+1]), abs(a[i+k-1]-a[pos+1])); int t = min(tp1, tp2); res = min(res, t); } printf("%d\n", res); }