题目链接:

http://codeforces.com/problemset/problem/660/C

题意:

给定0.1组成的数组,可以改变k个0使其为1,问最终可以得到的连续的1的最大长度。

分析:

很容易想到二分答案的做法,

二分长度,然后找是否存在满足题意的区间。

还可以用尺取法,这样在O(n)时间负责度内就可以完成,但是个人感觉写起来没有二分直观。。

代码:

二分:

#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
const int maxn = 300000 + 5;
int a[maxn];
int t[maxn];
int n, k;
int f1 = -1;
bool judge(int p)
{
for(int i = 0; i + p - 1< n; i++){
if(t[i + p - 1] - t[i - 1] + k >= p) {
f1 = i;
return true;
}
}
return false;
}
int main (void)
{
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
t[i] = t[i - 1] + (a[i] == 1);
}
int l = 0, r = n + 1;
while(l < r - 1){
int mid = (l + r) / 2;
if(judge(mid)) l = mid;
else r = mid;
}
printf("%d\n", l);
for(int i = 0; i < f1; i++){
printf("%d ", a[i]);
}
for(int i = f1; i < f1 + l; i++)
printf("1 ");
for(int i = max(f1 + l, 0); i < n; i++){
printf("%d ", a[i]);
}
return 0; }

尺取法:(two pointers)

#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
const int maxn = 300000 + 5;
int a[maxn], t[maxn];
int n, k;
int main (void)
{
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
int r = 0, cnt = 1, ans = 0, MAX = 0;
int f1 = -1, f2 = -1;
for(int i = 0; i < n; i++){
if(a[i - 1] == 0){
cnt--;
while(cnt <= k && r < n){
if(a[r] == 1){
r++;
}else{
if(cnt == k) {break;}
cnt++;
r++;
}
}
ans = r - i ;
}else ans--;
if(ans > MAX){
MAX = ans;
f1 = i;
f2 = r - 1;
}
}
cout<<MAX<<endl;
if(k == 0){
for(int i = 0; i < n; i++) cout<<a[i]<<' ';
return 0;
}
for(int i = 0; i < f1; i++) cout<<a[i]<<' ';
for(int i = f1; i <= f2; i++) cout<<1<<' ';
for(int i = f2 + 1; i < n; i++) cout<<a[i]<<' ';
return 0;
}

最新文章

  1. 【requireJS源码学习02】data-main加载的实现
  2. webpack配置命令
  3. 【Django】Django 定时任务实现(django-crontab+command)
  4. 存储过程返回布尔值以及C#相关处理
  5. 利用POI 技术动态替换word模板内容
  6. 真机调试 —— An unknown error occurred.
  7. POJ-A Simple Problem with Integers
  8. VI编辑器学习笔记
  9. ASP.NET中分布式事务的使用
  10. bzoj 4537 HNOI2016 最小公倍数
  11. 你学会UI设计了吗?
  12. C#入门基本概念
  13. Java高并发--缓存
  14. 我的第一个爬虫程序:利用Python抓取网页上的信息
  15. type=number 的maxlength和可以输入E的问题
  16. LeetCode(35) Search Insert Position
  17. kali64位 安装 adb
  18. EntityFramework定向加载实体
  19. Java之网络爬虫WebCollector2.1.2+selenium2.44+phantomjs2.1.1
  20. Idea查看代码相关技巧

热门文章

  1. SpringMvc之参数绑定注解详解
  2. C# 移动控件
  3. 洛谷 P3038 [USACO11DEC]牧草种植Grass Planting
  4. Bootstrap学习笔记之Nestable可拖拽树结构
  5. 前端基础入门第一阶段-Web前端开发基础环境配置
  6. MFC实现类似spy++dm取句柄功能
  7. 日常:论我的T3是如何苟掉的
  8. HTTP初步了解
  9. mysql启动问题
  10. LeetCode 304. Range Sum Query 2D – Immutable