2019.10.23-最长全1串(双指针)

题目描述:

给一个 01 的字符串,定义答案=该串中最长的连续 1 的长度,现在你有至多
K 次机会,每次机会可以将串中的某个 0 改成 1,现在问最大的可能答案.

输入描述:
输入第一行两个整数 N,K,表示字符串长度和机会次数
第二行输入 N 个整数,表示该字符串的元素

输出描述:
输出仅一行,表示答案

样例输入:
10 2
1 0 0 1 0 1 0 1 0 1
样例输出:
5
数据范围:
100%的数据保证:1 <= N <= 3*10^5 , 0 <= K <= N

双指针扫过,风一般得,只剩顽固的边界依旧,只剩对拍出错的叹息,改,耐心,那你就(A)了这道题了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++a)
#define nR(a,b,c) for(register int a = (b); a >= (c); --a)
#define Fill(a,b) memset(a, b, sizeof(a))
#define Swap(a,b) ((a) ^= (b) ^= (a) ^= (b))

#define ON_DEBUGG

#ifdef ON_DEBUGG

#define D_e_Line printf("-----------
")
#define D_e(x) std::cout << (#x) << " : " <<x << "
"
#define FileOpen() freopen("in.txt", "r", stdin)
#define FileSave() freopen("out.txt", "w", stdout)
#define Pause() system("pause")
#include <ctime>
#define TIME() fprintf(stderr, "
TIME : %.3lfms
", clock() * 1000.0 / CLOCKS_PER_SEC)

#else

#define D_e_Line ;
#define D_e(x) ;
#define FileOpen() ;
#define FilSave ;
#define Pause() ;
#define TIME() ;

#endif

struct ios {
	template<typename ATP> ios& operator >> (ATP &x) {
		x = 0; int f = 1; char c;
		for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
		while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
		x *= f;
		return *this;
	}
}io;

using namespace std;

template<typename ATP> inline ATP Min(ATP a, ATP b) {
	return a < b ? a : b;
}
template<typename ATP> inline ATP Max(ATP a, ATP b) {
	return a > b ? a : b;
}
template<typename ATP> inline ATP Abs(ATP a) {
	return a < 0 ? -a : a;
}

const int N = 3e5 + 7;

int a[N];
int main() {
freopen("A.in", "r", stdin);
freopen("A.out", "w", stdout);
	int n, K;
	io >> n >> K;
	R(i,1,n){
		io >> a[i];
	}
	int tot = 0, l = 1, r = 1, ans = 0;
	if(a[l] == 0) tot = 1;
	while(1){
//		printf("$%d %d %d %d
", l, r, ans, tot);
		if(a[r + 1] == 1){
			++r;
			if(r > n) break;
			ans = Max(ans, r - l + 1);
		}
		else{
			++r;
			++tot;
			while(tot > K){
				if(a[l] == 0) --tot;
				++l;
			}
			if(r > n) break;
			ans = Max(ans, r - l + 1);
		}
	}
	
	printf("%d", ans);
	
	return 0;
}
/*
10 4
0 1 1 0 1 1 1 0 0 1 
*/
/*
10 4
0 0 0 0 0 1 0 0 1 1 
*/
/*
30 12
0 1 1 0 1 1 1 0 0 0 1 0 1 0 0 1 1 1 1 1 0 1 0 0 1 0 0 0 0 0 

26
*/
/*
30 8
1 1 0 0 1 1 0 1 0 1 1 0 1 1 0 0 0 0 0 0 1 1 1 0 1 0 1 1 0 0 

3 17

17
*/
/*
30 3
1 0 0 1 1 1 1 1 0 1 0 0 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1 0 0 0 

10
*/
原文地址:https://www.cnblogs.com/bingoyes/p/11729549.html