Description
n个数字,求不相交的总和最大的最多k个连续子序列。
1<= k<= N<= 1000000。
Input
Output
Sample Input
5 2
7 -3 4 -9 5
Sample Output
13
HINT
Source
傻逼卡常数好题…又卡常数又卡内存
如果范围小,有非常显然的费用流做法.
然后范围大了,就考虑把费用流依靠线段树来实现增广就行了
实质性的操作就是区间取反.
复杂度是
O(qklogn)
因为这个题只有一组询问,所以就是
O(klogn)
四倍经验…
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define MAXN 1000010
#define lchild rt<<1,l,mid
#define rchild rt<<1|1,mid+1,r
#define ln rt<<1
#define rn rt<<1|1
#define GET (ch>='0'&&ch<='9')
#define LL long long
using namespace std;
inline void in(int &x)
{
char ch=getchar();x=0;int flag=1;
while (!GET) flag=ch=='-'?-1:1,ch=getchar();
while (GET) x=x*10+ch-'0',ch=getchar();x*=flag;
}
int n,k,top;
int a[MAXN];
struct node
{
int lpos,rpos,pos1,pos2;
LL maxn,sum,lval,rval;
inline void init(int pos,int val) { lpos=rpos=pos1=pos2=pos;lval=rval=maxn=sum=val; }
};
struct seg
{
int l,r;
bool flag;
node mx,mn;
inline void init(long long val) { mn.init(l,-val);mx.init(l,val); }
}tree[MAXN*2+200000];
inline node merge(const node &a,const node &b)
{
node ret;ret.sum=a.sum+b.sum;
ret.lval=a.lval;ret.lpos=a.lpos;
if (a.sum+b.lval>ret.lval) ret.lval=a.sum+b.lval,ret.lpos=b.lpos;
ret.rval=b.rval;ret.rpos=b.rpos;
if (b.sum+a.rval>ret.rval) ret.rval=b.sum+a.rval,ret.rpos=a.rpos;
ret.maxn=a.rval+b.lval;ret.pos1=a.rpos;ret.pos2=b.lpos;
if (ret.maxn<a.maxn) ret.maxn=a.maxn,ret.pos1=a.pos1,ret.pos2=a.pos2;
if (ret.maxn<b.maxn) ret.maxn=b.maxn,ret.pos1=b.pos1,ret.pos2=b.pos2;
return ret;
}
void build(int rt=1,int l=1,int r=n)
{
tree[rt].l=l;tree[rt].r=r;
if (l==r) { tree[rt].init(a[l]);return; }
int mid=(l+r)>>1;build(lchild);build(rchild);
tree[rt].mn=merge(tree[ln].mn,tree[rn].mn);
tree[rt].mx=merge(tree[ln].mx,tree[rn].mx);
}
void rev(int rt,int l,int r)
{
int L=tree[rt].l,R=tree[rt].r,mid=(L+R)>>1;
if (l<=L&&r>=R) { tree[rt].flag^=1;swap(tree[rt].mn,tree[rt].mx);return; }
if (tree[rt].flag)
{
tree[ln].flag^=1;tree[rn].flag^=1;
swap(tree[ln].mn,tree[ln].mx);swap(tree[rn].mn,tree[rn].mx);
tree[rt].flag^=1;
}
if (r<=mid) rev(ln,l,r);
else if (l>mid) rev(rn,l,r);
else rev(ln,l,mid),rev(rn,mid+1,r);
tree[rt].mn=merge(tree[ln].mn,tree[rn].mn);
tree[rt].mx=merge(tree[ln].mx,tree[rn].mx);
}
node query(int rt,int l,int r)
{
int L=tree[rt].l,R=tree[rt].r,mid=(L+R)>>1;
if (l<=L&&r>=R) return tree[rt].mx;
if (tree[rt].flag)
{
tree[ln].flag^=1;tree[rn].flag^=1;
swap(tree[ln].mn,tree[ln].mx);swap(tree[rn].mn,tree[rn].mx);
tree[rt].flag^=1;
}
if (r<=mid) return query(ln,l,r);
else if (l>mid) return query(rn,l,r);
else return merge(query(ln,l,mid),query(rn,mid+1,r));
}
struct Node { int l,r; }sta[MAXN];
inline void Query(int l,int r,int k)
{
long long ans=0;top=0;
while (k--)
{
node ret=query(1,l,r);
if (ret.maxn>0) ans+=ret.maxn; else break;
rev(1,ret.pos1,ret.pos2);sta[++top]=(Node){ret.pos1,ret.pos2};
}
cout<<ans<<endl;
}
int main()
{
in(n);in(k);
for (int i=1;i<=n;i++) in(a[i]);build();
Query(1,n,k);
}