题目描述:
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.
题意很简单,给一个长度为n的序列,你选择一个长度不超过k的连续子序列,使其和最大。注意这题序列可以首尾相连。
首先输入一个T表示样例个数,每组输入n,k和n个数,输出最大值和区间下标,下标从1开始。
样例:
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 -1ouput:
7 1 3 7 1 3 7 6 2 -1 1 1单调队列的应用,先求前缀和,因为求最大值,那么维护一个单调增的队列,维护时注意当当前元素与队首元素之差超过k的时候,就把队首弹出,这样就可以保证队列中的元素都在此时连续的k个元素之中同时保证队首元素是这个区间最小值,还要注意的是,你插入队列的元素应该为角标-1,因为你在用前缀和数组时,比如sum[2,3]!=pls[3]-pls[2]而是等于pls[3]-pls[1];
那么下面是AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXM=100010;
const int INF=1e9+7;
int n,k;
int a[2*MAXM];
int pls[2*MAXM];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(a,0,sizeof(a));
memset(pls,0,sizeof(pls));
scanf("%d%d",&n,&k);
for (int i=1;i<=n;i++)
scanf("%d",&a[i]);
int j=1;
for (int i=n+1;i<n+k;i++)
a[i]=a[j++];
for (int i=1;i<n+k;i++)
pls[i]=pls[i-1]+a[i];
deque<int > d1;
int maxm=-INF;
int l,r;
for (int i=1;i<n+k;i++)
{
while(!d1.empty()&&pls[i-1]<pls[d1.back()])
d1.pop_back();
while(!d1.empty()&&i-d1.front()>k)
d1.pop_front();
d1.push_back(i-1);
int sum=pls[i]-pls[d1.front()];
//printf("--%d\n",sum);
if (sum>maxm)
{
maxm=sum;
l=d1.front()+1;
r=i;
}
}
if (r>n)
r=r-n;
if (l>n)
l=l-n;
printf("%d %d %d\n",maxm,l,r);
}
return 0;
}