HDU 3415——Max Sum of Max-K-sub-sequence

来源:互联网 发布:pdf expert mac破解版 编辑:程序博客网 时间:2024/06/07 05:04

题目描述:

Given a circle sequence A11,A22,A33......Ann. Circle sequence means the left neighbour of A11 is Ann , and the right neighbour of Ann is A11
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:

46 36 -1 2 -6 5 -56 46 -1 2 -6 5 -56 3-1 2 -6 5 -5 66 6-1 -1 -1 -1 -1 -1
ouput:

7 1 37 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;}


原创粉丝点击