用户与s连边,边权为获利,用户向需要的基站连边边权为正无穷,基站向t连边,边权为费用,最后用总获利减去最
小割即可。
最大带权闭合子图:正权与s连边,边权为权值,负权与t连边,边权为权值的绝对值,原图之间的点连边边权为inf,跑最大流后用正权减去最小割,这里割掉和s连的边代表不选这个节点,割掉和t的连边代表选择这个节点
#include<cstdio>
#include<cstring>
#include<iostream>
#define maxn 1000021
#define inf 0x3fffffff
using namespace std;
int head[maxn],n,m,tot,h[maxn],all,last[maxn],ans,s,t,q[maxn];
struct edge{int v,next,w;}e[maxn];
void adde(int a,int b,int c){
e[tot].v=b,e[tot].next=head[a],e[tot].w=c;head[a]=tot++;
e[tot].v=a,e[tot].next=head[b],e[tot].w=0;head[b]=tot++;
}
bool bfs(){
for(int i=s;i<=t;i++)h[i]=-1;
int l=0,r=1;q[l]=s;h[s]=0;
while(l<r){
int u=q[l++];
for(int v,i=head[u];i!=-1;i=e[i].next){
if(h[v=e[i].v]==-1&&e[i].w){
h[v]=h[u]+1;
q[r++]=v;
}
}
}
return h[t]!=-1;
}
int dfs(int u,int f){
if(u==t||!f)return f;
int used=0,w;
for(int v,i=last[u];i!=-1;i=e[i].next){
last[u]=i;
if(h[v=e[i].v]!=h[u]+1||!e[i].w)continue;
w=min(e[i].w,f-used);
w=dfs(v,w);
e[i].w-=w,e[i^1].w+=w,used+=w;
if(used==f)return used;
}
if(!used)h[u]=-1;
return used;
}
void dinic(){
while(bfs()){
for(int i=s;i<=t;i++)last[i]=head[i];
ans+=dfs(s,inf);
}
}
void build(){
s=0,t=n+m+1;
for(int x,i=1;i<=n;i++){
scanf("%d",&x);
adde(m+i,t,x);
}
for(int a,b,c,i=1;i<=m;i++){
scanf("%d%d%d",&a,&b,&c);
all+=c;
adde(s,i,c),adde(i,m+a,inf),adde(i,m+b,inf);
}
}
int main(){
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
build();dinic();
printf("%d",all-ans);
return 0;
}