Max Sum of Max-K-sub-sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4883 Accepted Submission(s): 1780
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.
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).
用两种写法弄过,一种调用STL双向队列,一种是直接数组模拟,感觉模拟麻烦点但是耗时很少,双向队列每次都是调用的函数,所以耗时多。
STL双向队列:(734MS)
#include <iostream>
#include <queue>
using namespace std;
int a[222222],sum[222222]; //sum[n]记录从a[1]加到a[n]的和
deque<int> q;
int main (void)
{
int t,n,m,i,head,end,s;
cin>>t;
while(t--&&cin>>n>>m)
{
sum[0]=0;
for(i=1;i<=n;i++)
{
cin>>a[i];
sum[i]=sum[i-1]+a[i];
}
for(i=n+1;i<=n+m;i++)
sum[i]=sum[i-1]+a[i-n];
s=-1e10;head=end=0; //最大值初始化为-1e10
q.clear(); //把队列弄干净,初始化双向队列,清空
for(i=1;i<n+m;i++)
{
while(!q.empty()&&sum[i-1]<sum[q.back()]) //如果队列不是空的,而且当前数值压入队列会破坏队列元素单调
q.pop_back(); //那么把队尾元素出队
while(!q.empty()&&i-q.front()>m) //如果队列不是空的,而且当前记录的子串长度超过规定范围
q.pop_front(); //队首元素出队
q.push_back(i-1); //把当前数值压入队尾
if(sum[i]-sum[q.front()]>s) //当前元素满足条件的最大值大于记录的最大值时进行记录操作
{
s=sum[i]-sum[q.front()];
head=q.front()+1;end=i;
}
}
if(head>n)head-=n;
if(end>n)end-=n;
cout<<s<<" "<<head<<" "<<end<<endl;
}
return 0;
}
用数组模拟双向队列:(187MS)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[222222],sum[222222]={0},que[222222]; //que代替队列起记录作用,sum还是一样记录从1到n的和
int main (void)
{
int t,n,m,s,i,j,k,l,max,aa,ss,qian,hou;
scanf("%d",&t);
while(t--&&scanf("%d%d",&n,&m))
{
for(i=1;i<=n;i++)
scanf("%d",&a[i]),a[n+i]=a[i];
for(i=1,sum[0]=0;i<=n+m;i++)
sum[i]=sum[i-1]+a[i];
max=-1000000,aa=ss=qian=hou=0;
for(i=1;i<n+m;i++)
{
while(qian<hou&&sum[i-1]<sum[que[hou-1]])hou--; //hou即是队尾
que[hou++]=i-1; //压入队列数组
while(qian<hou&&i-que[qian]>m)qian++; /qian即是队首
if(sum[i]-sum[que[qian]]>max)
{
max=sum[i]-sum[que[qian]];
aa=que[qian]+1;ss=i;
}
}
if(aa>n)aa-=n;
if(ss>n)ss-=n;
printf("%d %d %d
",max,aa,ss);
}
return 0;
}