P3980 题解
考虑流建模,考虑以下关键 trick:可以同时使得两个部分所有边增加
对于本题,建模
然后就用无源汇可行流转换成有原汇最大流的办法做就好了。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+114;
const int maxm = 1e5+114;
const int inf = 1e9+114;
int pre[maxn],head[maxm<<1],vis[maxn],tot=1;
int flow[maxn];
int dis[maxn];
int s,t,maxflow,ans,n;
struct Node{
int v,w,nxt,val;
}e[maxm<<2];
inline void add(int u,int v,int w,int val){
e[++tot].v=v;
e[tot].nxt=head[u];
e[tot].w=w;
e[tot].val=val;
head[u]=tot;
e[++tot].v=u;
e[tot].nxt=head[v];
e[tot].w=0;
e[tot].val=-val;
head[v]=tot;
}
bool spfa(){
for(int i=1;i<=n;i++){
dis[i]=inf;
vis[i]=0;
}
queue<int> q;
flow[s]=inf;
vis[s]=true;
dis[s]=0;
q.push(s);
while(!q.empty()){
int u=q.front();
vis[u]=false;
q.pop();
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].v,cost=e[i].val;
if(e[i].w>0&&dis[u]+cost<dis[v]){
dis[v]=dis[u]+cost;
flow[v]=min(flow[u],e[i].w);
pre[v]=i;
if(vis[v]==false)
q.push(v),vis[v]=true;
}
}
}
return dis[t]<inf;
}
void update(){
int u=t;
while(u!=s){
e[pre[u]].w-=flow[t];
e[pre[u]^1].w+=flow[t];
u=e[pre[u]^1].v;
}
maxflow+=flow[t];
ans+=flow[t]*dis[t];
return ;
}
int N,M;
int a[maxn];
signed main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
//0 到 n n+1 个点,s=n+2,t=n+3
cin>>N>>M;
n=N+3;
s=N+2,t=N+3;
for(int i=1;i<=N;i++){
cin>>a[i];
}
for(int i=1;i+1<N+2;i++){
add(i,i+1,inf,0);
}
//流量平衡
for(int i=1;i<N+2;i++){
//进入的流量 a[i-1]
//出去的流量 a[i]
if(a[i-1]-a[i]>0){
add(s,i,a[i-1]-a[i],0);
}else if(a[i-1]-a[i]<0){
add(i,t,a[i]-a[i-1],0);
}
}
for(int i=1;i<=M;i++){
int s,t,c;
cin>>s>>t>>c;
add(t+1,s,inf,c);
}
while(spfa()==true) update();
cout<<ans<<"\n";
return 0;
}