題目描述
傳送門
題解
建原圖很簡單: 對(duì)于能到達(dá)的點(diǎn)x,y,x->y,[1,inf] s->i,[0,inf];i->t,[0,inf]
將原圖進(jìn)行改造 建立附加源匯ss,tt 對(duì)于原圖中有的邊x->y,[b,c],連邊x->y,c-b 記某一個(gè)點(diǎn)的權(quán)d(i)為所有流入這個(gè)點(diǎn)的邊的下界和-所有流出這個(gè)點(diǎn)的邊的下界和 若d(i)>0,連邊ss->i,d(i) 若d(i)<0,連邊i->tt,-d(i) 然后對(duì)ss->tt跑最大流 然后連邊t->s,inf 再對(duì)ss->tt跑最大流 此時(shí)t->s,inf這條邊的實(shí)際流量就是原圖中的最小流
代碼
#include<algorithm>#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<queue>using namespace std;#define N 110#define E 30005#define inf 1000000000int 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]<t) { 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);