1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define INF 10000000000000007
#define maxn 1010
#define maxm 10010
#define maxe 25000
#define ll long long
using namespace std;
ll c[maxm],v[maxn],w[maxe],cst[maxe],dis[maxn];
int n,m,s,t,e,a[maxm],b[maxm];
int fa[maxe],next[maxe],link[maxn],son[maxe],rec[maxe],opt[maxn],pre[maxn];
bool vis[maxn];
void add( int x, int y,ll z,ll cost){
fa[++e]=y;next[e]=link[x];link[x]=e;w[e]=z;cst[e]=cost;son[e]=x;rec[e]=e+1;
fa[++e]=x;next[e]=link[y];link[y]=e;w[e]=0;cst[e]=-cost;son[e]=y;rec[e]=e-1;
}
bool spfa(){
for ( int i=s;i<=t;i++) dis[i]=INF,vis[i]= true ;
dis[s]=0;vis[s]= false ; int head=0,tail=1;opt[1]=s;
while (head!=tail){
head=(head+1)%maxn;
for ( int x=opt[head],i=link[x];i;i=next[i]) if (w[i]&&dis[x]+cst[i]<dis[fa[i]]){
dis[fa[i]]=dis[x]+cst[i];pre[fa[i]]=i;
if (vis[fa[i]]) tail=(tail+1)%maxn,opt[tail]=fa[i],vis[fa[i]]= false ;
}
vis[opt[head]]= true ;
}
if (dis[t]!=INF) return true ; return false ;
}
ll MCMF(){
ll ans=0;
while (spfa()){
int u=t;ll mn=INF;
while (u!=s) mn=min(mn,w[pre[u]]),u=son[pre[u]];
u=t;
while (u!=s) w[pre[u]]-=mn,w[rec[pre[u]]]+=mn,ans+=mn*cst[pre[u]],u=son[pre[u]];
}
return ans;
}
int main(){
scanf ( "%d%d" ,&n,&m);
memset (c,0, sizeof (c));
memset (v,0, sizeof (v));
for ( int i=1;i<=n;i++) scanf ( "%lld" ,&v[i]);
for ( int i=n+1;i>=1;i--) v[i]=v[i]-v[i-1];
for ( int i=1;i<=m;i++) scanf ( "%d%d%lld" ,&a[i],&b[i],&c[i]);
s=0,t=n+2,e=0;
for ( int i=1;i<=n+1;i++) if (v[i]>0) add(s,i,v[i],0); else add(i,t,-v[i],0);
for ( int i=1;i<=m;i++) add(a[i],b[i]+1,INF,c[i]);
for ( int i=2;i<=n+1;i++) add(i,i-1,INF,0);
printf ( "%lld" ,MCMF());
return 0;
}
|