4
解题思路:看了po姐的建图,发现和我不一样,然后再看题目才知道是每一边都要经过。。。
我终于会打有上下界的网络流了。。。。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,len,S,T,TT,SS,ans;
const int INF=0x7fffffff;
int to[25000],next[25000],h[25000],zhi[25000];
int dis[250],q[300000];
int degree[250];
inline int read()
{
char y; int x=0,f=1;y=getchar();
while (y<'0' || y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0'&&y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
}
void ins(int x,int y,int flow)
{
++len; to[len]=y; next[len]=h[x]; zhi[len]=flow; h[x]=len;
}
void insert(int x,int y,int flow)
{
ins(x,y,flow);
ins(y,x,0);
}
bool bfs()
{
memset(dis,-1,sizeof(dis)); dis[S]=0; int tail=1,head=0; q[tail]=S;
while (head<tail)
{
++head;
int u=h[q[head]];
while (u!=0)
{
if (zhi[u]>0 && dis[to[u]]==-1)
{
dis[to[u]]=dis[q[head]]+1;
++tail; q[tail]=to[u];
}
u=next[u];
}
}
if (dis[T]!=-1) return true;else return false;
}
int dicnic(int now,int sum)
{
if (now==T)return sum;
int sug=0;
int u=h[now];
while (u!=0)
{
if (zhi[u]>0&&dis[to[u]]==dis[now]+1)
{
int s=dicnic(to[u],min(sum-sug,zhi[u]));
if (s)
{
zhi[u]-=s; zhi[u^1]+=s;
sug+=s;
if (sug==sum)return sug;
}
}
u=next[u];
}
if (sug==0)dis[now]=-1; return sug;
}
void getans()
{
int u=h[S];
while (u!=0)
{
zhi[u]=0; zhi[u^1]=0;
u=next[u];
}
u=h[T];
while (u!=0)
{
zhi[u]=0; zhi[u^1]=0;
u=next[u];
}
u=h[TT];
while (u!=0)
{
if (to[u]==SS)
{
ans=zhi[u^1];
zhi[u]=0; zhi[u^1]=0;
}
u=next[u];
}
}
int main()
{
n=read(); len=1;
S=2*n+1; T=2*n+2; SS=2*n+3; TT=2*n+4;
for (int i=1;i<=n;++i)
{
insert(SS,i,INF);
insert(i,TT,INF);
int x=read();
for (int j=1;j<=x;++j)
{
int y=read();
--degree[i];
++degree[y];
insert(i,y,INF);
}
}
for (int i=1;i<=n;++i)
{
if(degree[i]>0)
insert(S,i,degree[i]);
if(degree[i]<0)
insert(i,T,-degree[i]);
}
insert(TT,SS,INF);
while (bfs())
{
dicnic(S,0x7fffffff);
}
getans();
insert(S,TT,INF);
insert(SS,T,INF);
while (bfs())
{
ans-=dicnic(S,0x7fffffff);
}
printf("%d",ans);
}