题目链接:http://www.ifrog.cc/acm/problem/1124
1124 - 咸鱼魔法记
Time Limit:1s Memory Limit:128MByte
Submissions:416Solved:145
DESCRIPTION
给你一个01串,我们定义这个串的咸鱼值,是最长的全1串。现在你最多可以使用K次咸鱼魔法,每次魔法,你可以使得一个位置翻转(0变成1,1变成0)。问你这个串的咸鱼值最多是多少。
INPUT
第一行两个整数N,K。表示串的长度和可以施展咸鱼魔法的次数。(N,K<=300000)第二行N个01整数。
OUTPUT
输出答案。
SAMPLE INPUT
10 2
1 0 0 1 0 1 0 1 0 1
SAMPLE OUTPUT
5
SOLUTION
解析:暴力遍历一遍,一直尺取找最优解
代码:
#include<bits/stdc++.h>
#define N 300009
using namespace std;
typedef long long LL;
int a[N];
int main()
{
int n, k;
scanf("%d%d", &n, &k);
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
int l, r, ans = -1; l = r = 1;
for(int i = 1; i <= n; i++)
{
if(k <= 0 && a[i] == 0) break;
if(a[i] == 0) k--;
r++;
}
ans = r - l;
for(int i = r; i <= n; i++)
{
if(a[i] == 0)
{
ans = max(ans, i - l);
while(a[l] == 1) l++;
l++;
}
}
ans = max(n - l + 1, ans);
printf("%d\n", ans);
return 0;
}