Max Sum of Max-K-sub-sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4983 Accepted Submission(s): 1820
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
Author
shǎ崽@HDU
Source
题意:给出一个有N个数字(-1000..1000,N<=10^5)的环状序列,让你求一个和最大的连续子序列。这个连续子序列的长度小于等于K。
思路:
问题转化为求max(sum[i-j](i-j<=k)),这就是一个单调队列的问题了。枚举i,用一个单调队列维护一个递增序列,每次j取队首就够了。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 200005
using namespace std;
int n,m,k,ans,s,e;
int a[maxn],sum[maxn];
int sp,ep;
int c[maxn],id[maxn];
void push(int kk) // 单调队列维护一个递增序列
{
int i,j,t;
t=sum[kk];
i=ep;
while(i>=sp&&t<=c[i]) i--; // 注意要写i>=sp 开始WA了
ep=i+1;
c[ep]=t;
id[ep]=kk;
while(kk-id[sp]>=k) sp++;
}
void solve()
{
int i,j;
sp=ep=0;
c[0]=0;
id[0]=0;
ans=-1000000000;
for(i=1; i<=m; i++)
{
if(ans<sum[i]-c[sp])
{
ans=sum[i]-c[sp];
s=id[sp]+1;
e=i;
if(s>n) s-=n;
if(e>n) e-=n;
}
push(i);
}
}
int main()
{
int i,j,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
sum[0]=0;
for(i=1; i<=n; i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
m=n+k;
for(i=n+1; i<=m; i++)
{
sum[i]=sum[i-1]+a[i-n];
}
solve();
printf("%d %d %d\n",ans,s,e);
}
return 0;
}