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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章