TT的神秘任务3(单调队列优化DP)

问题描述

TT 猫咖的生意越来越红火,人越来越多,也越来越拥挤。

为了解决这个问题,TT 决定扩大营业规模,但猫从哪里来呢?

TT 第一时间想到了神秘人,想要再次通过完成任务的方式获得猫咪。

而这一次,神秘人决定加大难度。

给定一个环,A[1], A[2], A[3], … , A[n],其中 A[1] 的左边是 A[n]。要求从环上找出一段长度不超过 K 的连续序列,使其和最大。

这一次,TT 陷入了沉思,他需要你们的帮助。

Input

第一行一个整数 T,表示数据组数,不超过 100。

每组数据第一行给定两个整数 N K。(1 ≤ N ≤ 100000, 1 ≤ K ≤ N)

接下来一行,给出 N 个整数。(-1000 ≤ A[i] ≤ 1000)。

Output

对于每一组数据,输出满足条件的最大连续和以及起始位置和终止位置。

如果有多个结果,输出起始位置最小的,如果还是有多组结果,输出长度最短的。

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

解题思路

这个题严格来说并不算动态规划,更多偏向於单调队列。这个题有这样几条要求:

  • 环形拼接
  • 最大连续序列
  • 长度不超过k

环形拼接很简单,就是直接将1-n的数据复制一遍放在a[n+1]到a[2*n]里面就行了。(只放1-k也行)

最大连续序列也比较容易,贪心和dp都可以做到。我们可以定义f[i]为以ii为结尾的最大连续子序列和,那么答案就是max(f[i])

对于长度不超过k,我们可以将状态转移方程设为:f[i]=sum[i]min{sum[k]}(imki)f[i]=sum[i]-min\{sum[k]\}(i-m\le k\le i),其中sum[i]是前缀和,这样时间复杂度就是O(mn)O(m*n)

然后还可以用单调队列来进行优化,将时间复杂度降为O(n)O(n)。需要注意的一点是,加入队列的元素是sum[i1]sum[i-1]。因为对于区间[x,y][x,y]i=xya[i]=sum[y]sum[x1]\sum_{i=x}^{y}a[i]=sum[y]-sum[x-1]

完整代码

//#pragma GCC optimize(2)
//#pragma G++ optimize(2)
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
#include <deque>
#include <list>
using namespace std;

const int maxn=100000+10;
int t,n,k,a[maxn],sum[maxn*2],L,R,ans;
deque<int> q;
int getint(){
    int x=0,s=1; char ch=' ';
    while(ch<'0' || ch>'9'){ ch=getchar(); if(ch=='-') s=-1;}
    while(ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar();}
    return x*s;
}
int main(){
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    t=getint();
    while(t--){
        ans=INT_MIN; memset(sum,0,sizeof(sum));
        n=getint(); k=getint();
        for (int i=1; i<=n; i++) {
            a[i]=getint();
            sum[i]=sum[i-1]+a[i];
        }
        for (int i=n+1; i<=2*n; i++){
            sum[i]=sum[i-1]+a[i-n];
        }
        q.clear();
        for (int i=1; i<=2*n; i++){
            while(!q.empty() && sum[q.back()]>sum[i-1]) q.pop_back();
            q.push_back(i-1);
            if(i-q.front()>k) q.pop_front();
            if(sum[i]-sum[q.front()]>ans){
                ans=sum[i]-sum[q.front()];
                L=q.front()+1; R=i; if(R>n) R-=n;
            }
        }
        printf("%d %d %d\n",ans,L,R);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章