CC

自然万物都趋向从有序变得无序

0%

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

题目链接:点我

题目


    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.

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

题意:

求大小为k以内的子序列的最大和.

思路:

序列倍增,然后求前缀和,最后用前缀和维护一个下标差不超过m的单调递增的单调队列.

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;

const int maxn = 200000 + 10;
int sum[maxn];
int a[maxn];
int b[maxn];

int main(){
int t;
scanf("%d", &t);
while(t--){
int n, m;
scanf("%d %d", &n, &m);
for(int i = 1;i <= n;++i){
scanf("%d", &a[i]);
a[n+i]=a[i];
}
sum[0] = 0;
int ansl,ansr,ans=-100000000;
for(int i = 1; i <= n + n;++i){//找出序列中最大的数并且求前缀和
sum[i] = sum[i-1] + a[i];
if(a[i] > ans){
ans = a[i];
ansl =i;
ansr = i;
}
}
int l= 0 ,r ,k = 0;
for(int i = 1; i <= n + n;++i){
while( k > l && sum[b[k-1]]>sum[i-1]) k--;
b[k++] = i-1;
while(k > l && i - b[l] > m ) ++l;//单调队列的大小不超过m
if((ans <sum[i] - sum[b[l]] && i)){
ans = sum[i] - sum[b[l]];
ansl = b[l] + 1;
ansr = i;
}
}
if (ansl > n) ansl -= n;
if (ansr > n) ansr -= n;
printf("%d %d %d\n",ans ,ansl, ansr);
}
return 0;
}