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

很裸的一道单调队列题(把数列扩大一倍即可),但是要注意题目的比较条件(定义比较函数),不然会WA
 
 
代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

const int N=100010;
typedef pair<int,int> PII;

int T,n,k;
int a[N<<1],dp[N<<1];
PII que[N<<1];
int st,ed;
int ans,p1,p2;



bool cmp(const PII &a,const PII &b) {
    if(a.first!=b.first) return a.first<b.first;
    return a.second>b.second;
}


void push(int x,int p) {
    que[ed++]=PII(x,p);
    while(ed-st>=2 && cmp(que[ed-2],que[ed-1])) que[ed-2]=que[ed-1],ed--;
}


int getdec(int cur) {
    if(cur-k<0) return 0;
    else return a[cur-k];
}

__inline int readInt() {
    char ch=getchar();
    int ret=0,s=1;
    while(ch!='-' && (ch<'0'||ch>'9')) ch=getchar();
    if(ch=='-') s=-1,ch=getchar();
    while(ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar();
    return ret*s;
}

int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%d%d",&n,&k);
        for(int i=0;i<n;i++) a[i]=readInt();
        for(int i=n;i<n+k-1;i++) a[i]=a[i-n];
        for(int i=1;i<n+k-1;i++) a[i]+=a[i-1];
        st=ed=0;
        ans=a[0],p1=p2=0;
        for(int i=0;i<n+k-1;i++) {
            while(ed-st>=1 && que[st].second<=i-k) st++;
            push(a[i],i);
            int tans=que[st].first-getdec(i);
            if(tans>ans){
                ans=tans;
                int sta=i>=k?i-k+1:0;
                int end=que[st].second;
                p1=sta;p2=end;
            }
        }
        printf("%d %d %d\n",ans,p1%n+1,p2%n+1);
    }
    return 0;
}
posted @ 2012-08-28 23:22  编程菜菜  阅读(154)  评论(0编辑  收藏  举报