P7219 [JOISC2020] 星座 3 题解
线段树,dp
本题中的图具有极强的性质。
我们从一颗星星的控制范围入手来解决问题,容易发现,一颗星星向下的控制范围是许多矩形的叠合,而向上的控制范围是一个直到最顶上的一个矩形。
因此我们考虑线段树优化
我们考虑维护前缀
更新
利用刚才的性质,由于不会有区间穿过
于是我们得到了转移,维护后缀
#include<iostream>
#include<cstdio>
#include<algorithm>
#define N 200005
#define ll long long
using namespace std;
int n,m,a[N];
struct node
{
int x,y,c,L,R;
}p[N];
int r,q[N];
bool cmp1(const node &A,const node &B)
{
return A.x<B.x;
}
bool cmp2(const node &A,const node &B)
{
if (A.y!=B.y)
return A.y<B.y;
return A.x<B.x;
}
void calc1(int id)
{
p[id].L=1;
int L=1,R=r;
while (L<=R)
{
int mid(L+R >> 1);
if (a[q[mid]]>=p[id].y)
p[id].L=q[mid]+1,L=mid+1; else
R=mid-1;
}
}
void calc2(int id)
{
p[id].R=n;
int L=1,R=r;
while (L<=R)
{
int mid(L+R >> 1);
if (a[q[mid]]>=p[id].y)
p[id].R=q[mid]-1,L=mid+1; else
R=mid-1;
}
}
ll ans;
void ckmax(ll &x,ll y)
{
x=(x>y)?x:y;
}
struct pt
{
ll Mx,Tag;
};
struct seg
{
#define mx(p) tr[p].Mx
#define tag(p) tr[p].Tag
#define ls(p) (p << 1)
#define rs(p) (p << 1 | 1)
pt tr[N << 2];
void update(int p)
{
mx(p)=max(mx(ls(p)),mx(rs(p)));
}
void push_tag(int p,ll z)
{
mx(p)+=z,tag(p)+=z;
}
void push_down(int p)
{
if (tag(p))
{
push_tag(ls(p),tag(p));
push_tag(rs(p),tag(p));
tag(p)=0;
}
}
void modify(int p,int l,int r,int x,int y,ll z)
{
if (x>y)
return;
if (l==x && r==y)
{
push_tag(p,z);
return;
}
push_down(p);
int mid(l+r >> 1);
if (y<=mid)
modify(ls(p),l,mid,x,y,z); else
if (x>mid)
modify(rs(p),mid+1,r,x,y,z); else
{
modify(ls(p),l,mid,x,mid,z);
modify(rs(p),mid+1,r,mid+1,y,z);
}
update(p);
}
ll calc(int p,int l,int r,int x,int y)
{
if (x>y)
return 0;
if (l==x && r==y)
return mx(p);
push_down(p);
int mid(l+r >> 1);
if (y<=mid)
return calc(ls(p),l,mid,x,y); else
if (x>mid)
return calc(rs(p),mid+1,r,x,y); else
return max(calc(ls(p),l,mid,x,mid),calc(rs(p),mid+1,r,mid+1,y));
}
}s1,s2;
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;++i)
scanf("%d",&a[i]);
scanf("%d",&m);
for (int i=1;i<=m;++i)
scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].c);
sort(p+1,p+m+1,cmp1);
int l=1;
for (int i=1;i<=n;++i)
{
while (l<=m && p[l].x==i)
calc1(l),++l;
while (r && a[i]>=a[q[r]])
--r;
q[++r]=i;
}
r=0;
l=m;
for (int i=n;i;--i)
{
while (l && p[l].x==i)
calc2(l),--l;
while (r && a[i]>=a[q[r]])
--r;
q[++r]=i;
}
sort(p+1,p+m+1,cmp2);
for (int i=1;i<=m;++i)
{
int x(p[i].x),y(p[i].y),c(p[i].c),L(p[i].L),R(p[i].R);
ll lx(s1.calc(1,1,n,1,x-1)),rx(s2.calc(1,1,n,x+1,n));
ll cx(s1.calc(1,1,n,1,R)),dx(s2.calc(1,1,n,L,n));
ll ex(s2.calc(1,1,n,x+1,n)-s2.calc(1,1,n,R+1,n));
ll fx(s1.calc(1,1,n,1,x-1)-s1.calc(1,1,n,1,L-1));
if (cx<lx+c+ex)
s1.modify(1,1,n,R,n,lx+c+ex-cx);
if (dx<rx+c+fx)
s2.modify(1,1,n,1,L,rx+c+fx-dx);
}
ans=s1.calc(1,1,n,1,n);
ans=-ans;
for (int i=1;i<=m;++i)
ans+=p[i].c;
printf("%lld\n",ans);
return 0;
}