codeforces 676C Vasya and String 前缀数组+二分查找

C. Vasya and String (尺取法) C. Vasya and String 题目链接 大致题意: 给出一串只有a和b构成的字符串,字符串长度为n,可修改字符限制个数为k 求能得到的最长连续相同的字符串的长度 解题思路: 尺取法 维护区间内字符a的个数和字符b的个数 如果numa <= k || numb <= k,说明区间[l,r]可以修改为满足条件的情况,更新答案即可 AC代码: #include <bits/stdc++.h> #define rep(i, n) for (int i = 1; i <= 阅读详情

C. Vasya and String
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotesbeauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.

Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

Input

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change.

The second line contains the string, consisting of letters 'a' and 'b' only.

Output

Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

Examples
input
4 2
abba
output
4
input
8 1
aabaabaa
output
5
Note

In the first sample, Vasya can obtain both strings "aaaa" and "bbbb".

In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".


首先用一个整形数组a和b分别存放字符串s的前缀,使得a[i] - a[j - 1]为[i, j]区间上'a'的个数(仅仅是个数,不一定连续,b同理)

然后就查找能用至多k个元素填充使连续串最长的区间[i,l]

扫描字符串中的每个位置i,计算k有能力填充的以i为起点的最长的区间[i,l]的长度

如果对于每个位置i,在找区间[i,l]时用for循环遍历的话肯定会超时,采用二分查找将复杂度降到nlog(n)



#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn = 100000;
char s[maxn + 10];
int a[maxn + 1], b[maxn + 10];

int n, k;

bool check(int l, int r) {
	if (a[r] - a[l - 1] <= k || b[r] - b[l - 1] <= k) {
		return true;
	}
	return false;
}

int main()
{
	cin >> n >> k;
	scanf("%s", s + 1);
	for (int i = 1; i <= n; i++) {
		a[i] = a[i - 1] + (s[i] == 'a');
		b[i] = b[i - 1] + (s[i] == 'b');
	}
	int ans = -1;
	for (int i = 1; i <= n; i++) {
		int l = i, r = n;
		while (l <= r) {
			int mid = (l + r) >> 1;
			check(i, mid) ? l = mid + 1 : r = mid - 1;
		}
		ans = max(ans, r - i + 1);
	}
	cout << ans << endl;
	return 0;
}





LoRa模块选型指南:正点原子ATK-LORA-01与SX1278芯片深度评测(含实测距离/功耗数据) 本文深度评测了正点原子ATK-LORA-01与SX1278芯片的性能表现,通过实测数据展示其在复杂环境中的通信距离与功耗表现。特别适合智慧农业、工业监测等物联网应用场景,提供详细的配置指南和优化技巧,帮助开发者实现高效、低功耗的LoRa通信解决方案。 阅读详情

相关推荐

Shopee接口安全机制深度解析:从签名参数到稳定采集实战

本文深度解析了Shopee平台接口的安全机制,重点剖析了其核心签名参数`x-sap-ri`和`x-sap-sec`的动态生成逻辑。通过逆向分析与实战演示,文章提供了使用Python模拟签名算法、构建稳定数据采集方案的完整思路与代码框架,并探讨了应对密钥动态更新等长期运行挑战的策略。

weixin_29323049的博客 405

Codeforces 676C Vasya and String (两点法)

Codeforces 676C Vasya and String (两点法)

Tc的专栏 1881

【自然语言处理】【多模态】多模态综述:视觉语言预训练模型

多模态预训练模型综述、模型结构、损失函数、下游任务、CLIP

bqw的博客 7774

【题解】Vasya and String(贪心 + 尺取法)

八中OJ 洛谷 尺取法:顾名思义,像尺子一样取一段,借用挑战书上面的话说,尺取法通常是对数组保存一对下标,即所选取的区间的左右端点,然后根据实际情况不断地推进区间左右端点以得出答案。之所以需要掌握这个技巧,是因为尺取法比直接暴力枚举区间效率高很多,尤其是数据量大的时候,所以尺取法是一种高效的枚举区间的方法,一般用于求取有一定限制的区间个数或最短的区间等等。 贪心选择性质:算法中每一步选择都是...

cqbzlydd的博客 304

海康工业相机硬件触发与YOLOv5实时检测的工业自动化实践

本文详细介绍了如何将海康工业相机的硬件触发模式与YOLOv5目标检测模型相结合,构建一套高实时性的工业自动化质检系统。文章从产线痛点出发,深入解析了硬件接线、SDK回调取图的实战技巧(包括规避常见Bug),并展示了如何将YOLOv5封装为服务,最终通过Flask API串联业务逻辑,实现从精准触发到实时AI判断的完整落地流程。

k6l7m8n9的博客 510

RDKit实战:5分钟搞定药物分子相似性分析(附Python代码)

本文提供了一套基于RDKit的快速药物分子相似性分析实战指南。通过Python代码演示,从环境搭建、分子指纹(如Morgan指纹)计算到Tanimoto相似性排序与可视化验证,帮助研究者在5分钟内完成从海量化合物库中精准筛选潜在活性分子的全流程,提升药物发现效率。

weixin_29193359的博客 323

C. Vasya and String [思维]

C. Vasya and String 题意: 长为n,由a,b构成的串,可以做k次改变. 问最后最长的相等字串长度是多少. 思路:  k个肯定连续改的. 想了好久.......... #include&lt;bits/stdc++.h&gt; #define PI acos(-1.0) #define pb push_back #define F first #define S seco...

Haipai1998的博客 604

基于TMS320F28034的SCI技术简介

28034的SCI没有接入DMA总线,不过它的收发都有4级的FIFO,在一定程度上也能够缓解cpu的压力。 本文的设计思想如下: 接收:通过中断的方式,4级FIFO满后在中断里将RXDATA出栈。不过就存在这种情况,发送端发出的数据未必能填满4级FIFO,然而此时配置的是4级FIFO触发中断,所以这种情况下中断无法及时地触发。怎么办? 本文的做法是在主程序下循环读取FIFO。这样就可以确保在数据高速传输时,通过中断和主程序及时和有效地接收到总线的数据。(不过当总线波特率较低时可能中断是几...

weixin_48388779的博客 1414

Vasya and String(尺取法)

High school student Vasya got a string of length n as a birthday present. This string consists of letters ‘a’ and ‘b’ only. Vasya denotes beauty of the string as the maximum length of a substring (con...

amazingee的博客 576

Python爬虫实战:高效爬取中国专利数据库的完整指南

在当今信息爆炸的时代,专利数据作为技术创新的重要指标,对企业研发、市场分析和学术研究都具有极高价值。中国作为全球专利申请量最大的国家,其专利数据库包含了海量的技术创新信息。本文将详细介绍如何使用Python最新技术构建一个高效、稳定的中国专利数据库爬虫系统。中国专利数据库主要由国家知识产权局(CNIPA)维护,包含发明专利、实用新型专利和外观设计专利三大类。截至2023年,中国专利数据库已收录超过400万件发明专利和300万件实用新型专利。

2201_76125261的博客 1585

基于FPGA的UDP 通信(六)

本文基于FPGA和MATLAB对千兆以太网通信模块UDP数据发送(FPGA发送)进行联合调试。

记录所学,分享知识,结识挚友 4739

Vasya and String CodeForces 676C 前缀和+二分

给出一串长度为n的字符串,字符串中只有‘a’或者'b',我们可以改变 k 次字母,我们可以得到的相同的连续子串最长有多长。

Sheepsheep 257

stable diffusioncontrolNet 预处理器/模型的下载及安装使用教程

首先说明,controlNet 的模型 不同于stable diffusion 模型,这一点一定要区分清楚。下面提供多个ControlNet 预处理器+ 专用模型的百度网盘下载链接,都是由群友整理贡献,但各自包含的版本不同,大家可自行选择。推荐下载紫色链接内的模型,fp16版文件更小,稍微新一些的controlnet插件还添加了对control-lora的支持(注意,要求controlnet插件的版本比12月16号新(1.1.423以上)才能正常识别),推荐下载;

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 3408

Codeforces Round #354 (Div. 2) C. Vasya and String

题目链接: http://codeforces.com/contest/676/problem/C 题解: 把连续的一段压缩成一个数,对新的数组求前缀和,用两个指针从左到右线性扫一遍。 一段值改变一部分的情况考虑的不够周到,wa了两次。 #include<iostream> #include<cstdio> #include<cstring> ...

weixin_30892763的博客 97

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

双指针+思维 Codeforces Round #354 (Div. 2) C题 Vasya and String

Vasya and String High school student Vasya got a string of length n as a birthday present. This string consists of letters ‘a’ and ‘b’ only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equ

不知所云的博客 381

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Codeforces 676C - Vasya and String 详解(二分前缀和+尺取两种写法)

C. Vasya and String time limit per test  1 second memory limit per test  256 megabytes input  standard input output  standard output High school student Vasya got a stri

K键盘里的青春K 1443

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

codeforces c-Vasya and String(二分+前缀和)

C. Vasya and Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHigh school student Vasya got a string of length n as a birthday present. This s...

I_believe_CWJ的博客 459

Codeforce#354C. Vasya and String(前缀和二分or尺取)

C. Vasya and String time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output High school student Vasya got a string o

Rain 686

CodeForces 676C Vasya and String

High school student Vasya got a string of length n as a birthday present. This string consists of letters ‘a’ and ‘b’ only. Vasya denotes beauty of the string as the maximum length of a substring (cons

oinei的博客 267

【Codeforces】Vasya and String(二分、前缀和)

思路: 利用二分搜索和前缀和解决。 AC: #include<iostream> #include<algorithm> using namespace std; int n, k; string s; int sum[100005]; int check(int x) { for(int i=0 ; i+x<=n ; i++) { if (sum[i+x]-sum[i]>=x-k || sum[i + x]-sum[i]<=

skill_Carney的博客 337

codeforces 676C C. Vasya and String(二分)

题目链接: C. Vasya and String time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output High school student Vasya got a string of...

weixin_30920853的博客 156

Vasya and String CodeForces - 676C [二分查找 + 尺取法]

题目链接 题目大意: 给定一个只含a,b的字符串,可以将其中有限个数的a转化成b,b转化成a。 问获得的最大的连续的串的长度 Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 code 1 尺取法: #include #include #in

米兰的小科比 338

Codeforces Round #354 (Div. 2) C Vasya and String(尺取法二分)

思路:枚举结尾,然后暴力二分就好了,用前缀和预处理一下,那么前缀和之差,就是你需要改变的个数 #include using namespace std; const int maxn = 1e5+7; int n,k; int sum[maxn]; char s[maxn]; int main() { scanf("%d%d",&n,&k); scanf("%s",s+1)

围巾的ACM博客 855

Codeforces Round #354 (Div. 2) - C. Vasya and String

                                                C. Vasya and String题目链接:http://codeforces.com/problemset/problem/676/CDescriptionHigh school student Vasya got a string of length n as a birthday presen...

sortmin的博客 239

cf676c Vasya and String 尺取法裸题

C. Vasya and String time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output High school student Vasya got a string o

ctrss的博客 913

codeforces_676C. Vasya and String(二分)

C. Vasya and String time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output High school student Vasya got a string o

凳子 421
上一篇: ubuntu 无法使用 vim 系统剪贴板(或 :reg 无+号寄存器)
下一篇: PAT (Advanced Level) Practise 1003. Emergency (25) Dijstra扩展应用
Daemoonn
博客等级 码龄11年 42粉丝 198原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址