现在的位置: 首页 > 综合 > 正文

hdu3415 Max Sum of Max-K-sub-sequence

2018年04月23日 ⁄ 综合 ⁄ 共 1814字 ⁄ 字号 评论关闭

Max Sum of Max-K-sub-sequence

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


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
 


Recommend
lcy

单调队列。

设sum[i]为从头到第i个数的和,然后就是维护距离为k的最小sum值,答案就是sum[i]-sum[min],可以用双端队列的stl做,不过不会太简化代码量。

#include <stdio.h>

#define INF 999999999

typedef struct
{
    int val,num,now;
}Queue;

int a[200005];
int sum[200005];
Queue q[200005];

int main()
{
    int front,tail,k,i,j,n,T;
    Queue ans;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&k);
        for (i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        for (i=n+1;i<=2*n;i++)
        {
            a[i]=a[i-n];
        }
        n=2*n;
        sum[0]=0;
        for (i=1;i<=n;i++)
        {
            sum[i]=sum[i-1]+a[i];
        }
        front=tail=1;
        ans.val=-INF;
        for (i=1;i<=n;i++)
        {
            while(tail>front && sum[i-1]<q[tail-1].val) tail--;
            q[tail].val=sum[i-1];
            q[tail].num=i-1;
            tail++;
            if (i-q[front].num>k) front++;
            if (sum[i]-q[front].val>ans.val)
            {
                ans.val=sum[i]-q[front].val;
                ans.num=q[front].num+1;
                ans.now=i;
            }
        }
        printf("%d %d %d\n",ans.val,ans.num,ans.now-n/2>0?ans.now-n/2:ans.now);
    }
    return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.