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

Max Sum of Max-K-sub-sequence

Problem 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

 
单调队列,子段和[i, j] = 前缀和[1, i] - 前缀和[1, j-1]。
单调队列可以解决定长 k 的单调序列区间中的最优解问题!
即: dp(i) = max{ s(i-k+1), s(i-k+2),..., s(i) }
或者: dp(i) = min{ s(i-k+1), s(i-k+2),..., s(i) }
为保证单调性和定长k的限制,在每次插入后,都要丢弃队列中超出k长度区域的值(即不在区间 i-k+1 ~ i 内的值),直到队首在给定的k长度范围内,同时队首元素就是当前最优解。
 
 1 #include <vector>

 2 #include <cstdio>

 3 #include <queue>

 4 #include <algorithm>

 5 #include <climits>

 6 using namespace std;

 7 

 8 int T;

 9 int N, K;

10 vector<int> v;

11 deque<int> q;

12 

13 void solve() {

14     int sum = INT_MIN, start = 0, end = 0;

15     for (int i = 1; i <= N + K; ++i) {

16         while (!q.empty() && v[q.back()] > v[i]) q.pop_back();

17         q.push_back(i - 1);

18         while (i - q.front() > K) q.pop_front();

19         if (sum < v[i] - v[q.front()]) {

20             sum = v[i] - v[q.front()];

21             start = q.front() + 1;

22             end = i;

23         }

24     }

25     printf("%d %d %d\n", sum, start, end > N ? end - N : end);

26 }

27 

28 int main() {

29     scanf("%d", &T);

30     while (T--) {

31         scanf("%d %d", &N, &K);

32         v.resize(N + K + 1, 0);

33         for (int i = 1; i <= N; ++i) {

34             scanf("%d", &v[i]);

35             v[i] += v[i-1];

36         }

37         for (int i = N + 1; i <= N + K; ++i) {

38             v[i] = v[N] + v[i-N];

39         }

40         q.clear();

41         solve();

42     }

43     return 0;

44 }

 

你可能感兴趣的:(sequence)