Luo Gu P1714 cut the cake monotonous queue

URL: https://www.luogu.org/problem/P1714

Meaning of the questions:

We are given a sequence number $ n-$, $ k interval length is obtained and the maximum value of \ leq m $ a. ($ N \ leq 5e5, m \ leq 5e2 $).

answer:

The title request $ max (sum [i] -sum [j], (0 \ leq ij <m)) $, direct violence seeking will TLE, so we need to optimize data structure, because it is seeking $ max (sum [i ] -sum [j], (0 \ leq ij <m)) $, i.e. $ sum [i] -min (sum [j], j \ in [i-m + 1, i]) $, so monotonically to maintain a minimum incremental queue.

AC Code:

#include <iostream>
#include <algorithm>
#include <and>
using namespace std;
int num [500005];
long long sum[500005];
struct node
{
	long long sum;
	int pos;
	node(long long a,int b)
	{
		sum=a,pos=b;
	}
};
int main ()
{
	ios::sync_with_stdio(0);
	cin.tie (0);
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;++i)
		cin>>num[i],sum[i]=sum[i-1]+num[i];
	long long ans=-0x3f3f3f3f;
	deque<node>maxq;
	maxq.push_back(node(sum[0],0));
	for(int i=1;i<=n;++i)
	{
		ans=max(ans,sum[i]-maxq.front().sum);
		while(!maxq.empty()&&maxq.back().sum>=sum[i])
			maxq.pop_back();	
		maxq.push_back(node(sum[i],i));
		while(maxq.front().pos<i-m+1)
			maxq.pop_front();
	}
	cout<<ans<<endl;
	return 0; 
}

 

 

Guess you like

Origin www.cnblogs.com/Aya-Uchida/p/11300611.html