您的位置:首页 > 产品设计 > UI/UE

hdu3415 Max Sum of Max-K-sub-sequence 单调队列

2014-05-14 15:46 393 查看


Max Sum of Max-K-sub-sequence

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 5692 Accepted Submission(s): 2060

Problem Description

Given a circle sequence A[1],A[2],A[3]......A
. Circle sequence means the left neighbour of A[1] is A
, and the right neighbour of A
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的数字之和的最大值,并求出对应的首位位置
思路:这个题目属于常见题型,给定一组环状数列,求出其中长度不超过k的数字之和的最大值用到了前缀和的技巧,比如要求i,j间所有数字之和,可以提前在输入的时候 计算出从0~i的数字之和及从0~j的数字之和,那么sum[i~j]=sum[j]-sum[i];现在的问题是求出最大的sum[i~j].那么我们可以固定sum[j]的值,当sum[i]最小时,整个式子值最大,显然会用到单调递增队列,不断维护进队出队操作即可,保持单调递增队列的单调性不被破坏,则队头元素始终是最小的值。详见程序:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=1000000+100;
const int inf=0x3fffffff;
int n,k,head,tail;
int a[MAXN],sum[2*MAXN];
struct node
{
    int val,index;
}que[MAXN];
int main()
{
    //freopen("text.txt","r",stdin);
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&k);
        sum[0]=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            sum[i]=sum[i-1]+a[i];
        }
        for(int i=n+1;i<n+k;i++)
            sum[i]=sum[i-1]+a[i-n];
        head=tail=0;
        int start=1,end=1,ans=-inf;
        for(int i=1;i<n+k;i++)
        {
            while(head<tail && que[tail-1].val>sum[i-1]) tail--;
            que[tail].val=sum[i-1]; que[tail++].index=i-1;
            if(head<tail && que[head].index<i-k)
                head++;
            if(sum[i]-que[head].val>ans)
            {
                ans=sum[i]-que[head].val;
                start=que[head].index+1; end=i;
            }
        }
        if(end>n)
            end-=n;
         printf("%d %d %d\n", ans,start,end);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: