AtCoder Beginner Contest 229 - D - Longest X

原题链接

题面:

Problem Statement

Given is a string S consisting of  X and ..

You can do the following operation on S between 0 and K times (inclusive).

  • Replace a . with an X.

What is the maximum possible number of consecutive Xs in S after the operations?

Constraints

  • 1≤∣S∣≤2×10^5
  • Each character of S is X or ..
  • 0≤K≤2×10^5
  • K is an integer.

题意:

给定一个只包含 “X” 和 “ . ” 的字符串,至多能将 K 个 “ . ” 变成 “X” 。

问:在变换后的字符串中,连续出现的 “X” 的最大可能个数是多少?

题解:

很容易想到可以以 S 的每一个字符为左端,从左向右暴力枚举,求 K 个操作后连续 “X” 的最大值

但题目的约束条件不允许这么大的复杂度。

所以考虑先用前缀和 cnt[i] 记录 [ 0 , i ] 内 “ . ” 的个数,方便之后枚举时做到 O(1) 查询。

代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
#define int unsigned long long
#define endl '\n'
string s;
int k,cnt[200005];
signed main() 
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
 	cin>>s>>k;
 	int len=s.size();
	for(int i=0;i<len;i++)
	{
        //前缀和记录前i个格里'.'的数量 方便O(1)查询 
		if(s[i]=='.') cnt[i]=cnt[i-1]+1;
		else cnt[i]=cnt[i-1];
	}
	int r=0,ans=0;
	for(int l=0;l<len;l++)
	{
        //滑动窗口 
		while(r<len&&cnt[r]-cnt[l-1]<=k) r++;
        // cnt[r]-cnt[l-1] 指 [ l , r ] 这个区间内 '.' 的数量
        // 每次 while 保证 K 次操作都用完
		ans=max(ans,r-l);
        // 这里的 r 是无法满足条件的第一个下标
        // 因此 r-l 就是当前以 l 为左端的窗口下的结果
	}
	cout<<ans;
    return 0;   
}
/**************************************************************
    Problem: 21696
    User: 2021UPC016
    Language: C++
    Result: 正确
    Time:189 ms
    Memory:4148 kb
****************************************************************/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值