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

题目描述:

Given a circle sequence A 1 1,A 2 2,A 3 3......A n n. Circle sequence means the left neighbour of A 1 1 is A n n , and the right neighbour of A n n is A 1 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 -1
ouput:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值