传送门
建原图很简单:
对于能到达的点x,y,x->y,[1,inf]
s->i,[0,inf];i->t,[0,inf]
将原图进行改造
建立附加源汇ss,tt
对于原图中有的边x->y,[b,c],连边x->y,c-b
记某一个点的权d(i)为所有流入这个点的边的下界和-所有流出这个点的边的下界和
若d(i)>0,连边ss->i,d(i)
若d(i)<0,连边i->tt,-d(i)
然后对ss->tt跑最大流
然后连边t->s,inf
再对ss->tt跑最大流
此时t->s,inf这条边的实际流量就是原图中的最小流
#include
#include
#include
#include
#include
#include
using namespace std;
#define N 110
#define E 30005
#define inf 1000000000
int n,m,x,s,t,ss,tt,maxflow;
int tot,point[N],nxt[E],v[E],remain[E];
int d[N],deep[N],num[N],last[N],cur[N];
queue <int> q;
void addedge(int x,int y,int cap)
{
++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=cap;
++tot; nxt[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0;
}
void bfs(int t)
{
for (int i=1;i<=t;++i) deep[i]=t;
deep[t]=0;
for (int i=1;i<=t;++i) cur[i]=point[i];
while (!q.empty()) q.pop();
q.push(t);
while (!q.empty())
{
int now=q.front();q.pop();
for (int i=point[now];i!=-1;i=nxt[i])
if (deep[v[i]]==t&&remain[i^1])
{
deep[v[i]]=deep[now]+1;
q.push(v[i]);
}
}
}
int addflow(int s,int t)
{
int now=t,ans=inf;
while (now!=s)
{
ans=min(ans,remain[last[now]]);
now=v[last[now]^1];
}
now=t;
while (now!=s)
{
remain[last[now]]-=ans;
remain[last[now]^1]+=ans;
now=v[last[now]^1];
}
return ans;
}
void isap(int s,int t)
{
bfs(t);
for (int i=1;i<=t;++i) ++num[deep[i]];
int now=s;
while (deep[s]if (now==t)
{
maxflow+=addflow(s,t);
now=s;
}
bool has_find=false;
for (int i=cur[now];i!=-1;i=nxt[i])
if (deep[v[i]]+1==deep[now]&&remain[i])
{
has_find=true;
cur[now]=i;
last[v[i]]=i;
now=v[i];
break;
}
if (!has_find)
{
int minn=t-1;
for (int i=point[now];i!=-1;i=nxt[i])
if (remain[i]) minn=min(minn,deep[v[i]]);
if (!(--num[deep[now]])) break;
++num[deep[now]=minn+1];
cur[now]=point[now];
if (now!=s) now=v[last[now]^1];
}
}
}
int main()
{
tot=-1;memset(point,-1,sizeof(point));
scanf("%d",&n);
s=n+1,t=s+1,ss=t+1,tt=ss+1;
for (int i=1;i<=n;++i)
{
scanf("%d",&m);
while (m--)
{
scanf("%d",&x);
addedge(i,x,inf);
--d[i],++d[x];
}
addedge(s,i,inf);
addedge(i,t,inf);
}
for (int i=1;i<=t;++i)
{
if (d[i]>0) addedge(ss,i,d[i]);
if (d[i]<0) addedge(i,tt,-d[i]);
}
isap(ss,tt);
addedge(t,s,inf);
isap(ss,tt);
printf("%d\n",remain[tot]);
}