前置知识:相对大小的圆舞曲 —— 最小割多选一模型
基本思路:
- 最大权闭合子图的权值和等于总正权值减去最大流,即.
- 建图方法是S连正权值点(边权为点权),负权值点连T(边权为点权的绝对值),正负权值点相互连接(边权为INF).
- 证明见《最小割模型在信息学竞赛中的应用》第19页.
易错点:
- 不写余量优化的网络流等同于竭泽而渔.
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int MAXN=2e5+5,MAXM=1000010;
struct Edge{
int from,to,w,nxt;
}e[MAXM];
int head[MAXN],edgeCnt=1;
void addEdge(int u,int v,int w){
e[++edgeCnt].from=u;
e[edgeCnt].to=v;
e[edgeCnt].w=w;
e[edgeCnt].nxt=head[u];
head[u]=edgeCnt;
}
int s,t;
int d[MAXN];
bool bfs(){
memset(d,0,sizeof(d));
queue<int> q;
q.push(s);
d[s]=1;
while(!q.empty()){
int nowV=q.front();q.pop();
for(int i=head[nowV];i;i=e[i].nxt){
int nowNode=e[i].to;
if(e[i].w&&(!d[nowNode])){
d[nowNode]=d[nowV]+1;
if(nowNode==t)return 1;
q.push(nowNode);
}
}
}
return 0;
}
int Dinic(int x,int flow){
if(x==t)return flow;
int rest=flow;
for(int i=head[x];i&&rest;i=e[i].nxt){//余量优化(rest)
int nowV=e[i].to;
if(d[nowV]==d[x]+1&&e[i].w){
int k=Dinic(nowV,min(rest,e[i].w));
if(!k)d[nowV]=0;
e[i].w-=k,e[i^1].w+=k;
rest-=k;
}
}
return flow-rest;
}
const int INF=2e9;
int main(){
int n,m;
scanf("%d%d",&n,&m);
s=n+m+2,t=n+m+3;
for(int i=1;i<=n;i++){
int tmp;
scanf("%d",&tmp);
addEdge(i+m,t,tmp);
addEdge(t,i+m,0);
}
int sum=0;
for(int i=1;i<=m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
sum+=c;
addEdge(s,i,c);
addEdge(i,s,0);
addEdge(i,a+m,INF);
addEdge(m+a,i,0);
addEdge(i,b+m,INF);
addEdge(b+m,i,0);
}
int ans=0;
while(bfs())
ans+=Dinic(s,INF);
printf("%d\n",sum-ans);
return 0;
}