Description
Y sera 陷入了沉睡,幻境中它梦到一个长度为N 的序列{Ai}。
对于这个序列的每一个子串,定义其幻境值为这个子串的和,现在Y sera 希望选择K 个不同的子串并使得这K 个子串的幻境值之和最大。
然而由于梦境中的种种限制,这些子串的长度必须在L 到R 之间。
你需要告诉她,最大的幻境值之和。
Input
N K LR
A1 A2 … AN
Output
输出一行一个整数,表示答案。
Sample Input
2 1 1 2
-8464 -912
Sample Output
-912
Data Constraint
对于20% 的数据,有1 <= N, K <= 1000; 1 <= L < R <= N
对于另外10% 的数据,有1 <=N, K <= 10^5; 1 <= L = R <= N
对于另外10% 的数据,有1 <= N <= 10^5; K = 1; 1 <= L < R <= N
对于100% 的数据,有1 <= N, K <= 10^5; 1 <= L < R <= N, |Ai|<= 10^4
题解
区间的个数是很多的,
假设枚举一个区间的左端点i,那么很显然右端点是在(i+l-1)~(i+r-1)这里面。
求的是最大值,那么对于每一个左端点,
都可以知道以它作为左端点,满足区间长度在l,r之间的,
使得这个区间最大的右端点。
就先将这些区间加入一个堆,
每次取堆顶的,然后以这个最大值的位置,将区间分成两个部分,
再在两个小区间了吗分别求最大值。
code
#include<queue>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#define ll long long
#define N 100003
#define db double
#define P putchar
#define G getchar
#define mo 998244353
using namespace std;
char ch;
void read(int &n)
{
n=0;
ch=G();
while((ch<'0' || ch>'9') && ch!='-')ch=G();
ll w=1;
if(ch=='-')w=-1,ch=G();
while('0'<=ch && ch<='9')n=(n<<3)+(n<<1)+ch-'0',ch=G();
n*=w;
}
int max(int a,int b){return a>b?a:b;}
int min(int a,int b){return a<b?a:b;}
ll abs(ll x){return x<0?-x:x;}
ll sqr(ll x){return x*x;}
void write(ll x){if(x>9) write(x/10);P(x%10+'0');}
struct arr
{
int x;
ll s;
}b[N];
struct node
{
int x;
ll s;
}t[N*4],tt;
struct node1
{
int y,l,r,x;
ll s;
}ttt,w;
int n,k,l,r,a[N],tot,g[N],p;
int root[N],opl,opr;
ll s[N],L,R,mid,ans;
bool cmp(arr a,arr b)
{
return a.s<b.s;
}
priority_queue <node1> q;
bool operator <(node1 a,node1 b){
return a.s<b.s;
}
void make(int x,int l,int r)
{
if(l==r)
{
t[x].s=s[l];
t[x].x=l;
return;
}
int m=(l+r)>>1;
make(x+x,l,m);
make(x+x+1,m+1,r);
if(t[x+x].s>t[x+x+1].s)t[x]=t[x+x];else t[x]=t[x+x+1];
}
void work(int x,int l,int r)
{
if(opl<=l && r<=opr)
{
if(tt.s<t[x].s)tt=t[x];
return;
}
int m=(l+r)>>1;
if(opl<=m)work(x+x,l,m);
if(m<opr)work(x+x+1,m+1,r);
}
int main()
{
freopen("fantasy.in","r",stdin);
freopen("fantasy.out","w",stdout);
read(n);read(k);read(l);read(r);
for(int i=1;i<=n;i++)
read(a[i]),s[i]=s[i-1]+a[i];
make(1,1,n);
for(int i=1;i<=n;i++)
{
opl=i+l-1;opr=min(i+r-1,n);tt.s=-2147483647;
if(opl<=opr)work(1,1,n),ttt.y=i,ttt.l=opl,ttt.r=opr,ttt.x=tt.x,ttt.s=tt.s-s[i-1],q.push(ttt);
}
for(int i=1;i<=k;i++)
{
w=q.top();q.pop();
ans=ans+w.s;
//printf("%lld\n",w.s);
opr=w.x-1;opl=w.l;tt.s=-2147483647;
if(opl<=opr)work(1,1,n),ttt.y=w.y,ttt.l=opl,ttt.r=opr,ttt.x=tt.x,ttt.s=tt.s-s[w.y-1],q.push(ttt);
opl=w.x+1;opr=w.r;tt.s=-2147483647;
if(opl<=opr)work(1,1,n),ttt.y=w.y,ttt.l=opl,ttt.r=opr,ttt.x=tt.x,ttt.s=tt.s-s[w.y-1],q.push(ttt);
}
printf("%lld",ans);
}