Max Sum of Max-K-sub-sequence
Time Limit: 1000 MS Memory Limit: 32768KB 64bit IO Format: % I64d & % I64u
Submit StatusDescription
Given a circle sequence A [1], A [2], A [3] ...... A [n]. circle sequence means the left neighbor of A [1] is A [n], and the right neighbor 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 shoshould 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-1
Sample Output
7 1 3
7 1 3
7 6 2
-1 1 1
Priority queue. If we add n-1 to 1-n, we can convert the ring into a line. sum is used to calculate the combination, then sum [j]-sum [I] can be used for sum from I to j. This technique can also optimize sum! Then sum [I] is used as the priority queue, where j ranges from 0 to n + m. In this way, sum one by one!
# Include <iostream> # include <stdio. h> using namespace std; int num [250000], sum [250000], prim [250000]; int main () {int n, m, t, I, front, rear; scanf ("% d", & t); while (t --) {scanf ("% d", & n, & m); sum [0] = 0; for (I = 1; I <= n; I ++) {scanf ("% d", & num [I]); sum [I] = sum [I-1] + num [I]; // use a combination to simplify the operation} for (; I <= 2 * n; I ++) {sum [I] = sum [I-1] + num [I-n]; // the corresponding NUM corresponding to Part I-N greater than n} front = 0; rear = 0; int maxx =-1e10, sx = 0, ex = 0; for (I = 1; I <= n + m; I ++) {while (front <rear & sum [prim [rear-1]> sum [I-1]) // insert {rear --;} prim [rear ++] = I-1; while (front <rear & I-prim [front]> m) // remove the {front ++ ;} if (maxx <sum [I]-sum [prim [front]) // Save the maximum value and the corresponding coordinates {sx = prim [front] + 1; ex = I; maxx = sum [I]-sum [prim [front] ;}} if (sx> n) sx-= n; // note that a model larger than n is constructed, re-run if (ex> n) ex-= n; printf ("% d \ n", maxx, sx, ex);} return 0 ;}