题目链接:http://ifrog.cc/acm/problem/1124
这道题两种思路
- 1.二分答案加O(n)判断
- 2.直接O(n)尺取法,尺取出最大答案
二分代码:
#include<bits/stdc++.h>
using namespace std;
int arr[1000007];
int n, k;
bool judge(int x)
{
int res = 0;
for(int i=0; i<x; ++ i)
res += arr[i];
if(res + k >= x)
return true;
for(int i=x; i<n; ++ i)
{
res += arr[i] - arr[i-x];
if(res + k >= x)
return true;
}
return false;
}
int main()
{
while(scanf("%d%d", &n, &k) != EOF)
{
for(int i=0; i<n; ++ i)
scanf("%d", &arr[i]);
int b = 0, e = n;
while(b < e)
{
int mid = b + (e - b + 1) / 2;
if(judge(mid))
b = mid;
else
e = mid - 1;
}
printf("%d\n", b);
}
return 0;
}
尺取代码如下:
#include<bits/stdc++.h>
using namespace std;
int arr[300007];
int main()
{
int n, k;
while(scanf("%d%d", &n, &k)!=EOF)
{
for(int i=1; i<=n; ++ i)
scanf("%d", &arr[i]);
int mx = 0;
if(k == 0)
{
int res = 0;
for(int i=1; i<=n; ++ i)
{
if(arr[i] == 1)
res ++;
else
{
mx = max(mx, res);
res = 0;
}
}
printf("%d\n", res);
continue;
}
for(int b = 1, e = 0, res = 0; b <= n;)
{
while(e+1 <= n && res + (arr[e + 1] == 0) <= k)
res += (arr[++ e] == 0);
mx = max(mx, e - b + 1);
if(e + 1 > n)
break;
while(res == k && b <= e)
{
res -= (arr[b ++] == 0);
if(res < k)
break;
}
}
printf("%d\n", mx);
}
return 0;
}