这道题求一个图的最大权闭合子图
在国集队论文里面有这种题目的求法
对于图中原有的有向边,连一条流量为INF的边
建立源点s,向所有点权为正数的点连一条流量为点权的边
建立汇点t,向所有点权为负数的点连一条流量为点权相反数的边
然后求这个图的最小割,也就是最大流,就是最大权闭合子图的权值和
最后从源点s搜一下,除了s,其他能走到的点就是最大权闭合子图的节点
详细论证见《最小割模型在信息学竞赛中的应用》胡伯涛
注意:这道题要用long long
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <map>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#include <deque>
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define LL long long
#define Pair pair<int,int>
#define LOWBIT(x) x & (-x)
using namespace std;
const int MOD=1e9+7;
const LL INF=1e16;
const int magic=348;
int t,tot=1,head[10048],to[200048],nxt[200048];LL f[200048];
inline void addedge(int s,int t,LL cap)
{
to[++tot]=t;nxt[tot]=head[s];head[s]=tot;f[tot]=cap;
to[++tot]=s;nxt[tot]=head[t];head[t]=tot;f[tot]=0;
}
int n,e,cnt=0;
int a[10048];
bool visited[10048];
int depth[10048];queue<int> q;
bool bfs()
{
int i,x,y;
for (i=0;i<=t;i++) depth[i]=-1;
depth[0]=0;q.push(0);
while (!q.empty())
{
x=q.front();q.pop();
for (i=head[x];i;i=nxt[i])
{
y=to[i];
if (f[i] && depth[y]==-1)
{
depth[y]=depth[x]+1;
q.push(y);
}
}
}
//for (i=0;i<=t;i++) cout<<depth[i]<<' ';
//for (i=head[4];i;i=nxt[i]) cout<<to[i]<<' '<<f[i]<<endl;
//cout<<endl;
if (depth[t]==-1) return false; else return true;
}
LL dfs(int x,LL maxf)
{
if (x==t) return maxf;
int i,y;
LL minf,now,ans=0;
for (i=head[x];i;i=nxt[i])
{
y=to[i];
if (f[i] && depth[y]==depth[x]+1)
{
//if (x==4 && y==3) cout<<"*"<<endl;
minf=min(f[i],maxf-ans);
now=dfs(y,minf);
f[i]-=now;
f[i^1]+=now;
ans+=now;
}
}
return ans;
}
void Dfs(int x)
{
visited[x]=true;
cnt++;
for (int i=head[x];i;i=nxt[i])
if (f[i] && !visited[to[i]]) Dfs(to[i]);
}
int main ()
{
int i,x,y;
LL sum=0;
scanf("%d%d",&n,&e);
for (i=1;i<=n;i++) scanf("%d",&a[i]);
for (i=1;i<=e;i++)
{
scanf("%d%d",&x,&y);
addedge(x,y,INF);
}
t=n+1;
for (i=1;i<=n;i++)
{
if (a[i]>0)
{
addedge(0,i,a[i]);
sum+=a[i];
}
if (a[i]<0) addedge(i,t,-a[i]);
}
LL ans=0;
while (bfs()) ans+=dfs(0,INF);
//cout<<ans<<endl;
Dfs(0);
cout<<cnt-1<<' '<<sum-ans<<endl;
return 0;
}