【985系列】985的0-1串难题

本文探讨了如何通过修改一定数量的0为1来获得最长的连续1子串的问题。提出了两种解决方案,一种使用数组记录0的位置并计算区间内1的数量,另一种采用二分查找的方法。这两种方法都能有效地解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1895: 985的0-1串难题

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 270   Solved: 79

Submit Status Web Board

Description

985有一个长度为n的0-1串,已知他最多可以修改k次(每次修改一个字符即0->1 或者 1->0),他想知道连续的全1子串最长是多少。

Input

第一行输入一个整数t,代表有t组测试数据。
每组数据第一行输入两个整数n,k分别代笔上面的信息。
注:1 <= t <= 12,1 <= n <= 100000,0 <= k <= 100000。

Output

一个整数代表可以得到的最大长度。

Sample Input

2
6 3
010100
6 2
010100

Sample Output

5
4

HINT

Source




hpu


为什么说经典呢,因为本题思维过程很巧妙,你要1的连续的串最长就要把0改为1,不可能把1改为0;

然后用一个数组存储,下标存储0的个数,实际存储的是0在整个序列中出现的次序,就是第几次出现的。

如果k个0的区间内实际数组值序列相差最大就说明此区间1的个数最多,也就是题目所求。

注意要把整个串的前面和后面都加一个0。

ac代码:

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 100005;
int cu[N];
char s[N];
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int n,k,cnt=0;
		scanf("%d%d%s",&n,&k,s);
		cu[cnt++]=0;
		for(int l=0; l<n; l++) {
			if(s[l]=='0')
				cu[cnt++]=l+1;
		}
		cu[cnt++]=n+1;
		if(k>=cnt-2) {
			printf("%d\n",n);
			continue;
		}
		int ans=0;
		for(int i=k+1; i<cnt; i++) {
			ans=max(ans,cu[i]-cu[i-k-1]-1);
		}
		printf("%d\n",ans);
	}
	return 0;
}
我为什么说这题好呢,以为用二分也能做
ac代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100005;
char c[N];
int cnt[N];
int n,k;
void charge() {
	if(c[0]=='0') cnt[0]=1;
	for(int i=1; i<n; i++) {
		if(c[i]=='0')
			cnt[i]++;
		cnt[i]+=cnt[i-1];
		//printf("%d--\n",cnt[i]);
	}
}
bool judge(int mid) {
	if(cnt[mid-1]<=k) return true;
	for(int i=0; i+mid<n; i++) {
		if(cnt[i+mid]-cnt[i]<=k)
			return true;
	}
	return false;
}
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		scanf("%d%d%s",&n,&k,c);
		memset(cnt,0,sizeof(cnt));
		charge();
		int l=0,r=n;
		int mid,ans=0;
		while(l<=r) {
			mid=r+l>>1;
			if(judge(mid)) {
				ans=mid;
				l=mid+1;
			} else {
				r=mid-1;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}

题目地址:http://acm.zzuli.edu.cn/zzuliacm/problem.php?id=1895


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值