# [HZOI2016]COGS2587 你猜是不是dp - 线段树优化dp

$dp[i][0]=min_{j=1}^i \left\{dp[j-1][1]+s[i][0]-s[j-1][0]+\sum_{[l,r]\subseteq[j,i]and\ t=0}c\right\}$

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<vector>
#include<utility>
#define gc getchar()
#define mp make_pair
#define fir first
#define sec second
#define inf (INT_MIN/2+10)
#define N 10010
#define debug(x) cerr<<#x<<"="<<x
#define sp <<" "
#define ln <<endl
using namespace std;
typedef pair<int,int> pii;
inline int inn()
{
int x=0,s=1,ch;while(((ch=gc)<'0'||ch>'9')&&ch!='-');
if(ch^'-') x=ch^'0';else s=-1;
while((ch=gc)>='0'&&ch<='9') x=(x<<1)+(x<<3)+(ch^'0');
return s*x;
}
struct segment{
int l,r,f[2],pt[2];//0 : black, 1 : white
segment *ch[2];
}*rt;
int build(segment* &rt,int l,int r)
{
rt=new segment,rt->l=l,rt->r=r;int mid=(l+r)>>1;
if(l<r) build(rt->ch[0],l,mid),build(rt->ch[1],mid+1,r);
return rt->f[0]=rt->f[1]=0,rt->pt[0]=rt->pt[1]=0;
}
inline int update_tags(segment* &rt,int v,int k) { return rt->f[k]+=v,rt->pt[k]+=v; }
inline int push_down(segment* &rt,int k)
{
update_tags(rt->ch[0],rt->pt[k],k),
update_tags(rt->ch[1],rt->pt[k],k),
rt->pt[k]=0;return 0;
}
int update(segment* &rt,int s,int t,int v,int k)
{
int l=rt->l,r=rt->r,mid=(l+r)>>1;
if(s<=l&&r<=t) return update_tags(rt,v,k);
if(rt->pt[k]) push_down(rt,k);
if(s<=mid) update(rt->ch[0],s,t,v,k);
if(mid<t) update(rt->ch[1],s,t,v,k);
return rt->f[k]=max(rt->ch[0]->f[k],rt->ch[1]->f[k]);
}
inline int update(segment* &rt,int p,int v,int k) { return update(rt,p,p,v,k); }
int query(segment* &rt,int s,int t,int k)
{
int l=rt->l,r=rt->r,mid=(l+r)>>1,ans=inf;
if(s<=l&&r<=t) return rt->f[k];
if(rt->pt[k]) push_down(rt,k);
if(s<=mid) ans=max(ans,query(rt->ch[0],s,t,k));
if(mid<t) ans=max(ans,query(rt->ch[1],s,t,k));
return ans;
}
int s[N][2],dp[N][2];vector<pair<pii,int> > v[N];
int show(segment* &rt)
{
static int f[2];f[0]=rt->f[0],f[1]=rt->f[1];
static int pt[2];pt[0]=rt->pt[0],pt[1]=rt->pt[1];
int l=rt->l,r=rt->r;debug(l)sp,debug(r)sp;
debug(f[0])sp,debug(f[1])sp,debug(pt[0])sp,debug(pt[1])ln;
if(l<r) show(rt->ch[0]),show(rt->ch[1]);return 0;
}
int main()
{
int n=inn()+1,m=inn(),t,l,r;build(rt,1,n);
for(int j=0;j<=1;j++)
for(int i=2;i<=n;i++) s[i][j]=s[i-1][j]+inn();
update(rt,1,0,0),update(rt,1,0,1);
while(m--)
t=inn()-1,l=inn()+1,r=inn()+1,
v[r].push_back(mp(mp(l,inn()),t));
for(int i=2;i<=n;i++)
{
for(int j=0;j<(int)v[i].size();j++)
update(rt,1,v[i][j].fir.fir-1,v[i][j].fir.sec,v[i][j].sec);
//      show(rt);cerr ln;
for(int j=0;j<=1;j++) dp[i][j]=query(rt,1,i-1,j)+s[i][j];
for(int j=0;j<=1;j++) update(rt,i,dp[i][j^1]-s[i][j],j);
//      show(rt);cerr ln;
}
//  for(int i=2;i<=n;i++) debug(dp[i][0])sp,debug(dp[i][1])ln;
return !printf("%d\n",max(dp[n][0],dp[n][1]));
}