您的位置:首页 > 其它

单调队列之求最大和

2014-03-26 15:08 344 查看
hdu
3415 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)



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


题意:
给出一组数列,求出其最大和,并标出起始位置和终止位置

分析:
这道题和12年地大邀请赛的一道题目有些类似,不过那道题数据量比较小,好像只有1000左右,所以直接构造一个2*N的数组模拟循环然后暴力查找一把就行了,但这道题暴力的话肯定会超时,所以还得用一个单调队列来优化一下,同时,因为数据输入比较多,在没有优化输入输出的情况下,建议在提交的时候用G++提交,那样会节省很多时间
代码如下:
#include<iostream>
#include<cstdio>
#define MIN -1e10
using namespace std;

int sum[200050]={0},Q[200050];
int main()
{
int T,N,K,i,temp,maxs,start,ends;
scanf("%d",&T);
while(T--)
{
int fronts=0,rear=0;
scanf("%d %d",&N,&K);
maxs = MIN;start=1,ends=1;
for(i=1;i<=N;i++)
{
scanf("%d",&temp);
sum[i] = sum [i-1] + temp;
sum[N+i]=temp;
}
for(;i<=2*N;i++)//构成一个循环
{
sum[i] += sum[i-1];
}
for(i=1;i<=K+N;i++)
{
while(fronts<rear&&(sum[Q[rear-1]]>sum[i-1]))//产生一个单调递增数列,注意要保证
rear--;                                 //每次入队时只能是当前位置的前一个元素
Q[rear++]=i-1;
while(fronts<rear&&(i-Q[fronts]>K))//保证队列的长度不超过K
fronts++;
if(sum[i]-sum[Q[fronts]]>maxs)//将当前位置的和减去队列中最小的和,并判断是否有一个新的最大值产生
{
maxs = sum[i]-sum[Q[fronts]]; //注意是当前和减去当前位置前面所求的和,不能包括其本身,
start = Q[fronts]+1;
ends  = i;

}
}
if(start>N) start -= N;
if(ends>N)  ends -= N;
printf("%d %d %d\n",maxs,start,ends);
}
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: