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

hdu3415 Max Sum of Max-K-sub-sequence(单调队列求n个数中和的最大值)

2013-07-21 10:24 381 查看


Max Sum of Max-K-sub-sequence

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

Total Submission(s): 4836 Accepted Submission(s): 1765



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


题意:在组成环的n个数中求出不超过m个连续的数相加之和最大时的最大值、起始位置和终止位置(如果大于n则要减去n)
这个题我觉得还是有必要做一做的,虽然跟以前做的那个单调队列题有点像,可是这个求和的我还是第一次做
#include<stdio.h>
int a[100005],sum[200005],q[200005];
int main()
{
int t,n,m,i,j,maxx,e,s,first,last;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
sum[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
for(;i<=n+m;i++)
sum[i]=sum[i-1]+a[i-n];//向后延伸m,这样就可以达到循环的效果
first=last=0;
q[last++]=0;//这要注意,WA好多次了,还是对单调队列理解的不够
maxx=a[1];
e=s=1;
for(i=1;i<=n+m;i++)
{
while(first<last&&sum[q[last-1]]>sum[i-1])//找最小值?因为我们看的是sum[i]-sum[q[first]],而sum[i]是定值
//所以要使这一项最大就必须使sum[q[first]]在m的范围内最小
{
last--;
}
q[last++]=i-1;//记录的也是i-1
while(first<last&&q[first]<i-m)//超出范围的去掉
first++;
if(maxx<sum[i]-sum[q[first]])
{
s=q[first]+1;//,我们当时记录的是i-1,这里要算起始点那就要加1
e=i;//终止点
maxx=sum[i]-sum[q[first]];//最大值
}
}
if(s>n)//这两句话千万别掉了
s-=n;
if(e>n)
e-=n;
printf("%d %d %d\n",maxx,s,e);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: