HDU Max Sum of Max-K-sub-sequence Monotonic queue

  • Max Sum of Max-K-sub-sequence

  • Meaning
    of the question Given a circular sequence with N numbers (N<=10^5), let you find a continuous subsequence with the largest sum. The length of this continuous subsequence is less than or equal to K.


  • The blog of this big guy that the idea borrowed from After
    reading the idea, I knocked WA. Then I looked at the code of the big guy, but I didn’t quite understand it. I traversed it. Why would sum[i-1] be operated on? When I asked for tmp, I used sum[i] again. Later I wanted to understand. .
    If i is traversed, the monotonic queue is used to maintain the interval [sum [i − k], sum [i + 1 − k]..., Sum [i − 1]] [sum[ik],sum[i+1 -k]...,sum[i-1]][sum[ik],sum[i+1k]...,sum[i1 ] ] The minimum value of these k numbers, the subscript of this minimum value is the left end point of the interval that satisfies the condition, and i is the right end point. The size of this interval is less than or equal to k. Consider the extreme casesum [i − k] sum [ik]sum[ik]的值最小,tmp= s u m [ i ] − s u m [ i − k ] sum[i]-sum[i-k] sum[i]sum[iThe value of k ] is the sum of the k numbers [i-k+1,i] in the sequence. So every time I try to fill in the queue, sum[i-1] is used, and sum[i] is used when seeking tmp at the end.

  • Code

#pragma GCC optimize(2)
#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
#define pi acos(-1.0)
#define e exp(1.0)
#define pb push_back
#define mk make_pair
#define fir first
#define sec second
#define scf scanf
#define prf printf
typedef pair<ll,ll> pa;
const ll INF=0x3f3f3f3f3f3f3f3f;
const ll MAX_T=120;
const ll MAX_N=1e5+7;
ll a[MAX_N],sum[MAX_N<<1],N,K,T;
deque<ll>DQ;
int main()
{
    
    
//  freopen(".../.txt","w",stdout);
//  freopen(".../.txt","r",stdin);
   ios::sync_with_stdio(false);
   cin>>T;
   while(T--){
    
    
   	cin>>N>>K;
   	DQ.clear();
   	ll i,j,k,maxx=-INF,resl=-1,resr=-1;
   	sum[0]=0;
   	for(i=1;i<=N;i++){
    
    
   		cin>>a[i];
   		sum[i]=sum[i-1]+a[i];
   	}
   	for(i=1;i<=K;i++){
    
    
   		sum[i+N]=sum[i+N-1]+a[i]; 
   	}
   	for(i=1;i<=N+K-1;i++){
    
    
   		while(!DQ.empty()&&sum[i-1]<sum[DQ.back()]){
    
    
   			DQ.pop_back();
   		} 
   		DQ.push_back(i-1);
   		while(!DQ.empty()&&i-DQ.front()>K){
    
    
   			DQ.pop_front();
   		}
   		ll tmp=sum[i]-sum[DQ.front()]; 
   		if(tmp>maxx){
    
    
   			maxx=tmp;
   			resl=DQ.front()+1;
   			resr=i;
   		}
   	}
   	cout<<maxx<<" "<<(resl-1+N)%N+1<<" "<<(resr-1+N)%N+1<<endl;
   }
   return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43311695/article/details/108734060