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

Source: Internet
Author: User

HDU_3415

Because the original sequence is a ring, in order to facilitate the processing, the K-1 elements can be supplemented at the end of the sequence, thus becoming a chain. If I is set to A [I], f [I] is the largest sum of the right boundary over item I, then f [I] = max {A [I]-A [j]} (I-K <= j <I ), so we can use A monotonous queue to maintain the smallest A [j] that we have encountered so far, and I-K <= j <I.

Because the sequence is not empty (or j <I) is required, the insert operation should be done at the end, at the same time, you must insert an element with a label of 0 and a value of 0 into the queue at the beginning.

#include<stdio.h>
#include<string.h>
#define MAXD 200010
#define INF 1000000000
int N, K, f[MAXD], x[MAXD], A[MAXD], q[MAXD], d[MAXD];
void init()
{
int i, j;
scanf("%d%d", &N, &K);
for(i = 1; i <= N; i ++)
scanf("%d", &x[i]);
A[0] = 0;
for(i = 1; i <= N; i ++)
{
A[i] = x[i];
A[i] += A[i - 1];
}
for(i = N + 1; i < N + K; i ++)
{
A[i] = x[i - N];
A[i] += A[i - 1];
}
}
void solve()
{
int i, j, front, rear, a, b, max, sum;
front = rear = 0;
max = - INF;
d[rear] = 0;
q[rear] = 0;
rear ++;
for(i = 1; i < N + K; i ++)
{
while(front < rear && d[front] < i - K)
front ++;
sum = A[i] - A[d[front]];
if(sum > max)
{
max = sum;
a = d[front];
b = i;
}
while(front < rear && q[rear - 1] > A[i])
rear --;
q[rear] = A[i];
d[rear] = i;
rear ++;
}
if(b > N)
b -= N;
printf("%d %d %d\n", max, a + 1, b);
}
int main()
{
int t;
scanf("%d", &t);
while(t --)
{
init();
solve();
}
return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.