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

来源:互联网 发布:淘宝司法拍卖后悔报名 编辑:程序博客网 时间:2024/05/21 17:41
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
46 36 -1 2 -6 5 -56 46 -1 2 -6 5 -56 3-1 2 -6 5 -5 66 6-1 -1 -1 -1 -1 -1
 

Sample Output
7 1 37 1 37 6 2-1 1 1

因为序列是环状的,所以可以在序列后面复制一段(或者复制前k - 1个数字)。如果用s[i]来表示复制过后的序列的前i个数的和,那么任意一个子序列[i..j]的和就等于s[j]-s[i-1]。对于每一个j,用s[j]减去最小的一个s[i](i>=j-k+1)就可以得到以j为终点长度不大于k的和最大的序列了。将原问题转化为这样一个问题后,就可以用单调队列解决了分析,先把这个问题解决思路转换成一个可行的办法,这里用到了单调递增队列,在序列后边复制一段,如果要表示一个集合[i,j],那么可以用sum[j]-sum[i-1]来表示,这里的i应该满足i>=j-k+1。

维护方法:对于每个j,我们插入s[j-1](为什么不是s[j]? 队列里面维护的是区间开始的下标,j是区间结束的下标),插入时从队尾插入。为了保证队列的单调性,我们从队尾开始删除元素,直到队尾元素比当前需要插入的元素优(本题中是值比待插入元素小,位置比待插入元素靠前,不过后面这一个条件可以不考虑),就将当前元素插入到队尾。之所以可以将之前的队列尾部元素全部删除,是因为它们已经不可能成为最优的元素了,因为当前要插入的元素位置比它们靠前,值比它们小。我们要找的,是满足(i>=j-k+1)的i中最小的s[i],位置越大越可能成为后面的j的最优s[i]。

在插入元素后,从队首开始,将不符合限制条件(i>=j-k+1)的元素全部删除,此时队列一定不为空。(因为刚刚插入了一个一定符合条件的元素)

#include<stdio.h>#include<string.h>#include<math.h>#include<iostream>#include<algorithm>#include<queue>#include<stack>using namespace std;#define ll long long#define getMax(a,b) a>b?a:b#define getMin(a,b) a<b?a:bconst int N=1e+5+5;int a[N],sum[N],h,e;int main(){    int t,n,k,i;    scanf("%d",&t);    while (t--)    {        int ans=-1<<30;        scanf("%d%d",&n,&k);        sum[0]=0;        for (i=1;i<=n;i++)        {              scanf("%d",&a[i]);              sum[i]=sum[i-1]+a[i];        }          for (i=n+1;i<n+k;i++)            sum[i]=sum[i-1]+a[i-n];        deque<int> q;        q.clear();        for (i=1;i<n+k;i++)        {            while (!q.empty()&&sum[i-1]<sum[q.back()])                q.pop_back();            while (!q.empty()&&q.front()<i-k)                q.pop_front();                q.push_back(i-1);            if (sum[i]-sum[q.front()]>ans)                {                    ans=sum[i]-sum[q.front()];                    h=q.front()+1;                    e=i;                }        }        if (e>n)        e%=n;        printf("%d %d %d\n",ans,h,e);    }    return 0;}


0 0
原创粉丝点击