题目传送门
。
解法:
线段树。
枚举左端点,用线段树维护以每个点作为右端点的答案。
对于不同的左端点,右端点的答案是不一样的。
设当前位置为i,电影为x,好看值为w,下个出现的位置为nxt。
在统计完以i为左端点的答案后。
我们需要往下枚举左端点。
这时候我们就算过了i这个位置。
要消除它对答案的影响。
那么从以位置i到nxt-1为右端点都无法再获得x的好看值。
那么i到nxt-1都减去w。
当右端点大于等于nxt的时候,又可以重新获得x的好看值。
但是看两次就会得不到好看值。所以右端点在nxt到x再下一个出现的位置-1都要加上w。
过程用线段树维护咯
代码实现:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
struct node {int lc,rc,l,r;ll lazy,c;}tr[2100000];int trlen;
void bt(int l,int r) {
int now=++trlen;tr[now].l=l;tr[now].r=r;tr[now].lc=tr[now].rc=-1;tr[now].c=0;tr[now].lazy=0;
if(l<r) {int mid=(l+r)/2;tr[now].lc=trlen+1;bt(l,mid);tr[now].rc=trlen+1;bt(mid+1,r);}
}
void update(int now) {
int lc=tr[now].lc,rc=tr[now].rc;
if(lc==-1)return ;
tr[lc].c+=tr[now].lazy;tr[rc].c+=tr[now].lazy;
tr[lc].lazy+=tr[now].lazy;tr[rc].lazy+=tr[now].lazy;tr[now].lazy=0;
}
void change(int now,int l,int r,ll k) {
if(tr[now].l==l&&tr[now].r==r) {tr[now].c+=k;tr[now].lazy+=k;return ;}
if(tr[now].lazy)update(now);
int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)/2;
if(r<=mid)change(lc,l,r,k);else if(l>mid)change(rc,l,r,k);
else {change(lc,l,mid,k);change(rc,mid+1,r,k);}
tr[now].c=max(tr[lc].c,tr[rc].c);
}
int head[1100000],last[1100000],next[1100000],a[1100000];
ll s[1100000];
int main() {
int n,m;scanf("%d%d",&n,&m);
memset(head,0,sizeof(head));
memset(last,0,sizeof(last));
memset(next,0,sizeof(next));
for(int i=1;i<=n;i++) {
scanf("%d",&a[i]);if(head[a[i]]==0)head[a[i]]=i;
next[last[a[i]]]=i;last[a[i]]=i;
}
for(int i=1;i<=m;i++)scanf("%lld",&s[i]);
trlen=0;bt(1,n);
for(int i=1;i<=m;i++) if(head[i]!=0) {
if(next[head[i]]==0)change(1,head[i],n,s[i]);
else change(1,head[i],next[head[i]]-1,s[i]);
}
ll ans=0;
for(int i=1;i<=n;i++) {
ans=max(ans,tr[1].c);
int nxt=next[i];
if(nxt!=0) {
change(1,i,nxt-1,-s[a[i]]);
if(next[nxt]==0)change(1,nxt,n,s[a[i]]);
else change(1,nxt,next[nxt]-1,s[a[i]]);
}else change(1,i,n,-s[a[i]]);
}printf("%lld\n",ans);
return 0;
}