现在的位置: 首页 > 综合 > 正文

单调队列的一个应用——求解连续区间最大值(HDU Max Sum of Max-K-sub-sequence)

2013年12月13日 ⁄ 综合 ⁄ 共 1870字 ⁄ 字号 评论关闭

Description

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.
 

Input

The first line of the input contains an integer T(1<=T<=100) which means the number of test cases.
Then T lines follow, each line starts with two integers N , K(1<=N<=100000 , 1<=K<=N), then N integers followed(all the integers are between -1000 and 1000).
 

Output

For each test case, you should output a line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the minimum
start position, if still more than one , output the minimum length of them.
 

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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN = 100010;
int N, K;
int a[MAXN];
int sum[2 * MAXN];

/*
 * 由于是统计不超过K个连续元素和的最大值,我们以sum值作为处理对象。
 * 思想:线性枚举当前状态,并且维护在K范围内的最小值,对就是用单调
 * 队列取维护当前允许范围内的最小值,然后求出当前最有解去更新总体的最优解即可
 * 很简单的,实际上就应该是传说中的斜率优化。理解万岁,为什么当年就是想不出来呢?
 */

struct node {
    int num, index;
} que[2 * MAXN];
int front, tail;

void init() {
    front = 0, tail = -1;
}

void Insert(int pos, int num) {
    if (front > tail) {
        front = tail = 0;
        que[front].index = pos;
        que[front].num = num;
        return;
    }
    while (front <= tail && que[tail].num >= num) tail--;
    que[++tail].index = pos;
    que[tail].num = num;
    while (front <= tail && pos - que[front].index + 1 > K) front++;
}

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &N, &K);
        init();
        sum[0] = 0;
        for (int i = 1; i <= N; i++) {
            scanf("%d", &a[i]);
            sum[i] = sum[i - 1] + a[i];
        }

        for (int i = 1; i <= N; i++) {
            sum[i + N] = sum[i + N - 1] + a[i];
        }
        int l, r;
        int ans = -100000000;
        Insert(0, sum[0]);
        for (int i = 1; i <= 2 * N; i++) {
            if (sum[i] - que[front].num > ans) {
                ans = sum[i] - que[front].num;
                l = que[front].index + 1;
                r = i;
            }
            Insert(i, sum[i]);
        }
        if (l > N) l -= N;
        if (r > N) r -= N;
        printf("%d %d %d\n", ans, l, r);
    }
    return 0;
}

抱歉!评论已关闭.