题面:
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 anX
.
What is the maximum possible number of consecutive X
s 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
****************************************************************/