Codeforces Round #756 F Sliding Window

Question link https://codeforces.com/contest/1611/problem/F

Recently I was brushing up on the sliding window (which I forgot about during review), and I came across a question that seemed very typical and I recorded it.

The purpose of the question is to give you an initial value of the money in the ATM. How many people come to withdraw or deposit money, and the maximum length can meet the requirements (the money is enough when withdrawing money)

The essence of the sliding window is that two pointers traverse the interval. If the interval meets the conditions, the optimal value is recorded. This interval can be fixed or unfixed, and this question is about the unfixed interval length.

The following is a sliding window algorithm template with no fixed length

l is the left pointer, r is the right pointer, and n is the right boundary.


     while(r<=n)
	 {
        while(r<=n)
	 	{   
            r++
	 	    直到区间不符合答案
	 	}
	 	if(可以取最值)
	 	{
	 	    记录答案
		}
		
		while(l<=r)
		{  
            l++
            直到区间符合答案
		}
	 }

The following is the AC code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+5;
int a[N];
void work()
{
	 int n;
	 ll s;
	 scanf("%d%lld",&n,&s);
	 for(int i=1;i<=n;i++)
	 scanf("%lld",&a[i]);
	 
	 a[n+1]=-1e16;//这里最后一个要赋一个最小值来防止最优区间r=n
	 int ansl=0,ansr=0,l=0,r=0,mx=0;
	 ll tmp=s;
	 while(r<=n)
	 {
        while(r<=n)
	 	{   
	 	    r++;
	 	    tmp+=a[r];
	 	    if(tmp<0) break;//右指针右移,直到答案不符合
	 	}
	 	if(r-l-1>mx)
	 	{
	 	    ansl=l+1,ansr=r-1,mx=r-l-1;	//更新答案
		}
		
		while(l<=r)
		{
			l++;
			tmp-=a[l];
			if(tmp>=0) break;//左指针左移,直到答案符合
		}
	 }
	 
	 if(mx>0) cout<<ansl<<" "<<ansr<<"\n";
	 else cout<<-1<<"\n";
}

int main()
{
    int q;
	 cin>>q;
    while(q--)
        work();
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_30798083/article/details/124669878