思路:
放个题解好吧.
http://www.cnblogs.com/zyfzyf/p/4114774.html
//By SiriusRen #include <queue> #include <cstdio> #include <algorithm> using namespace std; const int N=100050; int a[N],s[N],top,n,m,add,minu,tot,next[N],pre[N],vis[N]; struct Node{int v,id;Node(){}Node(int x,int y){v=x,id=y;}}; bool operator<(Node a,Node b){return a.v>b.v;} priority_queue<Node>pq; long long ans; signed main(){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); if(a[i]>0){ add+=a[i]; if(minu&&top)s[++top]=minu; minu=0; } else if(a[i]<0){ minu+=a[i]; if(add)s[++top]=add; add=0; } } if(add)s[++top]=add; for(int i=1;i<=top;i++){ if(s[i]>0)pq.push(Node(s[i],i)),tot++,ans+=s[i]; else pq.push(Node(-s[i],i)),s[i]=-s[i]; next[i]=i+1,pre[i]=i-1; }next[top]=0; if(tot<=m){ printf("%d ",ans); return 0; } else{ for(int i=1;i<=tot-m;i++){ Node tp=pq.top();pq.pop(); while(vis[tp.id]&&!pq.empty()) tp=pq.top(),pq.pop(); if(vis[tp.id])break; ans-=tp.v; if(pq.empty())break; int x=tp.id; if(!pre[x]){ vis[next[x]]=vis[x]=1;pre[next[next[x]]]=0; } else if(!next[x]){ vis[x]=vis[pre[x]]=1;next[pre[pre[x]]]=0; } else{ vis[pre[x]]=vis[next[x]]=1; tp.v=s[x]=s[pre[x]]+s[next[x]]-s[x]; if(next[next[x]])pre[next[next[x]]]=x; if(pre[pre[x]])next[pre[pre[x]]]=x; pre[x]=pre[pre[x]];next[x]=next[next[x]]; pq.push(tp); } } printf("%d ",ans); } }
//By SiriusRen #include <queue> #include <cstdio> #include <algorithm> using namespace std; const int N=100050; int a[N],s[N],top,n,m,add,minu,tot,next[N],pre[N],vis[N]; struct Node{ int v,id;Node(){}Node( int x, int y){v=x,id=y;}}; bool operator<(Node a,Node b){ return a.v>b.v;} priority_queue<Node>pq; long long ans; signed main(){ scanf ( "%d%d" ,&n,&m); for ( int i=1;i<=n;i++){ scanf ( "%d" ,&a[i]); if (a[i]>0){ add+=a[i]; if (minu&&top)s[++top]=minu; minu=0; } else if (a[i]<0){ minu+=a[i]; if (add)s[++top]=add; add=0; } } if (add)s[++top]=add; for ( int i=1;i<=top;i++){ if (s[i]>0)pq.push(Node(s[i],i)),tot++,ans+=s[i]; else pq.push(Node(-s[i],i)),s[i]=-s[i]; next[i]=i+1,pre[i]=i-1; }next[top]=0; if (tot<=m){ printf ( "%d
" ,ans); return 0; } else { for ( int i=1;i<=tot-m;i++){ // for(int j=1;j<=top;j++)printf("%d ",next[j]);puts(""); // printf("ans=%d
",ans); Node tp=pq.top();pq.pop(); while (vis[tp.id]&&!pq.empty()) tp=pq.top(),pq.pop(); if (vis[tp.id]) break ; ans-=tp.v; // printf("v=%d
",tp.v); if (pq.empty()) break ; int x=tp.id; if (!pre[x]){ vis[next[x]]=vis[x]=1;pre[next[next[x]]]=0; } else if (!next[x]){ vis[x]=vis[pre[x]]=1;next[pre[pre[x]]]=0; } else { vis[pre[x]]=vis[next[x]]=1; tp.v=s[x]=s[pre[x]]+s[next[x]]-s[x]; if (next[next[x]])pre[next[next[x]]]=x; if (pre[pre[x]])next[pre[pre[x]]]=x; pre[x]=pre[pre[x]];next[x]=next[next[x]]; pq.push(tp); } // for(int j=1;j<=top;j++)printf("%d ",next[j]);puts(""); } printf ( "%d
" ,ans); } } |