P14576 Lamborghini (Remix)
首先要知道两个性质:
1.相邻两个光标之间的距离永远不变。常识性问题不说了。
2.所有光标的所在行一定相邻。因为隔一行放光标空出来的这一行一定还能再放一个光标。
我们可以这么设想:所有光标全部移到了字符数最多的一行,这样的话光标数是最多的。
所以,我们的目标就变成了这样:在 中找出一个整数序列,使这个序列的和最大且不超过序列 中的最大值。
至此,此题变为双指针模板题。
AC 代码:
#include<bits/stdc++.h>
using namespace std;
long long a[200010];
void solve(){
int n;
long long mx = 0;
cin>>n;
for(int i = 1;i<=n;i++){
cin>>a[i];
a[i]++;//计算邻行的字符距离(加上换行)。
mx = max(mx,a[i]);//找最多字符的一行。
}
mx--;//去掉换行
long long l = 1,r = 1;//双指针。
long long sum = 0,maxx = 0;
while(r<=n){
if(sum>mx){//超过了最大值,舍弃 L 行的光标。
l++;
sum-=a[l];
}
else{//可以再容纳一个光标。
maxx = max(maxx,r-l+1);//计算最大值。
r++;
sum+=a[r];//加上字符数。
}
}
cout<<maxx<<'\n';
}
int main(){
cin.tie(0)->sync_with_stdio(0);
cout.tie(0);
int T;
cin>>T;
while(T--)solve();
return 0;
}时间复杂度 。