Max Sum of Max-K-sub-sequence (单调队列)

Max Sum of Max-K-sub-sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9826    Accepted Submission(s): 3639


 

Problem Description

Given a circle sequence A[1],A[2],A[3]......A[n]. Circle sequence means the left neighbour of A[1] is A[n] , and the right neighbour of A[n] is A[1].
Now your job is to calculate the max sum of a Max-K-sub-sequence. Max-K-sub-sequence means a continuous non-empty sub-sequence which length not exceed K.

Input

The first line of the input contains an integer T(1<=T<=100) which means the number of test cases.
Then T lines follow, each line starts with two integers N , K(1<=N<=100000 , 1<=K<=N), then N integers followed(all the integers are between -1000 and 1000).

Output

For each test case, you should output a line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the minimum start position, if still more than one , output the minimum length of them.

Sample Input

 

4 6 3 6 -1 2 -6 5 -5 6 4 6 -1 2 -6 5 -5 6 3 -1 2 -6 5 -5 6 6 6 -1 -1 -1 -1 -1 -1

Sample Output

 

7 1 3 7 1 3 7 6 2 -1 1 1

Author

shǎ崽@HDU

Source

HDOJ Monthly Contest – 2010.06.05

Recommend

lcy   |   We have carefully selected several similar problems for you:  3423 3417 3418 3419 3421 

题意:选取一个区间,长度<=k,使得该区间sum最大。输出sum起点终点。是个环状。

思路:如果k是定值直接用dp就好。但是该题的k是不定的。想到滑动窗口。这里利用的deque来进行模拟。可以从队首队尾进行删除操作,只能从队尾进行add操作。

思想就是维护一个单调递增的序列,每一次都是用当前的值剪掉之前的最小值,这样的和一定是最大的。

具体:递增单调队列来维护前缀和sum[maxn]。
队首就是区间内的sum最小值,那么sum[i]-min(sum[j])就是当前的最大。

(这道题还蛮好的)

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=200000+100;
int a[maxn],sum[maxn];
deque<int>De;
int main()
{
    int t,n,k;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&k);
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            a[i+n]=a[i];
        }
        De.clear();
        sum[0]=0;
        for(int i=1;i<=n+k-1;i++){
            sum[i]=sum[i-1]+a[i];
        }
     ///   cout<<"&&&&"<<endl;
        int shou,wei;
        int ans=-1000000000;
        for(int i=1;i<=n+k-1;i++){
         ///   cout<<"###########"<<endl;
            while(!De.empty() && sum[i-1]<sum[De.back()])
                De.pop_back();
            while(!De.empty() && De.front()<=i-k-1)
                De.pop_front();
            De.push_back(i-1);
            if(sum[i]-sum[De.front()]>ans){
                ans=sum[i]-sum[De.front()];
                shou=De.front()+1;
                if(i>n)
                    wei=i%n;
                else
                    wei=i;
            }
            De.push_back(i-1);
        }
        printf("%d %d %d\n",ans,shou,wei);
    }
}
发布了565 篇原创文章 · 获赞 110 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/xianpingping/article/details/86913052