5 5 8 -8 -10 12 -10 1 2 2 5 1 4 3 4 4 5
2
建图】源点向正权点加边,容量为权值;负权点向汇点加边,容量为权的绝对值;有限制关系的点加边,容量为INF。
【定理】最大权闭合图 = 正权值和 - 最小割
#include<cstdio>
#include<cstring>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<stack>
#include<queue>
#include <iomanip>
#include<iostream>
#include<algorithm>
using namespace std ;
const int N=600 ;
const int M=222222 ;
const int inf=1<<30 ;
struct node
{
int u ,v ,c,next ;
}edge[M];
int pre[N],head[N],gap[N],cur[N],dis[N];
int s,t,NV,top ;
void add(int u, int v , int c)
{
edge[top].u=u;
edge[top].v=v;
edge[top].c=c;
edge[top].next=head[u];
head[u]=top++;
edge[top].u=v;
edge[top].v=u;
edge[top].c=0;
edge[top].next=head[v];
head[v]=top++;
}
int sap()
{
memset(dis,0,sizeof(dis));
memset(gap,0,sizeof(gap));
memset(pre,-1,sizeof(pre));
for(int i = 0 ; i < NV ; ++i)
cur[i] = head[i];
int u = pre[s] = s,maxflow = 0,aug = inf;
gap[0] = NV;
while(dis[s] < NV)
{
loop:
for(int &i = cur[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if(edge[i].c && dis[u] == dis[v] + 1)
{
aug=min(aug,edge[i].c);
pre[v] = u;
u = v;
if(v == t)
{
maxflow += aug;
for(u = pre[u]; v != s; v = u,u = pre[u])
{
edge[cur[u]].c -= aug;
edge[cur[u]^1].c += aug;
}
aug =inf;
}
goto loop;
}
}
if( (--gap[dis[u]]) == 0) break;
int mindis = NV;
for(int i = head[u]; i != -1 ; i = edge[i].next)
{
int v = edge[i].v;
if(edge[i].c && mindis > dis[v])
{
cur[u] = i;
mindis = dis[v];
}
}
gap[ dis[u] = mindis+1 ] ++;
u = pre[u];
}
return maxflow;
}
int main()
{
int n , m , a,b,x ;
while(~scanf("%d%d",&n,&m))
{
top=0;
memset(head,-1,sizeof(head));
int sum=0;
for(int i = 1 ; i <= n ; i++)
{
scanf("%d",&x);
if(x>0)
{
add(0,i,x);
sum +=x ;
}
else add(i,n+1,-x);
}
for(int i = 1 ; i <= m ; i++)
{
scanf("%d%d",&a,&b);
add(a,b,inf);
}
s=0;t=n+1;NV=t+1;
printf("%d\n",sum-sap());
}
return 0;
}