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.
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).
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-1个数,因为(j,j+1,...i)的和可以用sum[i]-sum[j-1]表示,所以可以用原题可以转换成求数字长度不大于k的最大区间和。
#include<iostream> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<map> #include<string> using namespace std; #define maxn 100005 #define inf 88888888 int a[maxn],s[2*maxn]; int q[2*maxn][2]; int main() { int T,n,m,i,j,sum,start,end,front,rear; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); s[0]=0; for(i=1;i<=n;i++){ scanf("%d",&a[i]); s[i]=s[i-1]+a[i]; } for(i=n+1;i<=n+m-1;i++){ s[i]=s[i-1]+a[i-n]; } sum=-inf;front=1;rear=0; for(i=1;i<=n+m-1;i++){ while(front<=rear && s[i-1]<=q[rear][0])rear--;//这里每次维护i-1,因为之后的i减去q[front][1]可以直接得到[j,i]的sum值 rear++; q[rear][0]=s[i-1]; q[rear][1]=i; while(front<=rear && q[front][1]+m-1<i)front++; if(s[i]-q[front][0]>sum){ sum=s[i]-q[front][0]; start=q[front][1]; end=i; } } if(end>n)end=end%n; printf("%d %d %d\n",sum,start,end); } return 0; }