提交时间:2022-07-19 11:52:57
运行 ID: 52325
#include <bits/stdc++.h> using namespace std; int n,m,s,t; const int M=3e6+100; const int K=5e3; const int N=8e3+100; const int INF=1e9+10; int Head[N],To[M],W[M],Nxt[M],E=1,Htmp[N]; void Addedge(int x,int y) { W[++E]=1; To[E]=y; Nxt[E]=Head[x]; Head[x]=E; W[++E]=0; To[E]=x; Nxt[E]=Head[y]; Head[y]=E; } int Dep[N]; queue<int>Q; bool BFS() { for(int i=1; i<=n; i++) Htmp[i]=Head[i]; memset(Dep,0,sizeof(Dep)); Q.push(s); Dep[s]=1; while(!Q.empty()) { int u=Q.front(); Q.pop(); for(int i=Head[u]; i; i=Nxt[i]) { int v=To[i]; if(W[i]&&!Dep[v]) { Dep[v]=Dep[u]+1; Q.push(v); } } } return Dep[t]; } int DFS(int u,int prf) { if(!prf||u==t) return prf; int flow=0,del; for(int i=Htmp[u]; i; i=Nxt[i]) { Htmp[u]=i; int v=To[i]; if(Dep[v]!=Dep[u]+1||W[i]<=0) continue; del=DFS(v,min(prf,W[i])); if(del) { flow+=del; prf-=del; if(u!=s) for(int j=Head[u]; j; j=Nxt[j]) W[j]-=del,W[j^1]+=del; if(!prf) break; } } if(!flow) Dep[u]=0; return flow; } int Dinic() { int ret=0; while(BFS()) ret+=DFS(s,INF); return ret; } inline int Read() { int x=0,f=1; char ch=getchar(); while(!isdigit(ch)) { if(ch=='-') f=-1; ch=getchar(); } while(isdigit(ch)) { x=(x<<1)+(x<<3)+ch-'0'; ch=getchar(); } return x*f; } int main() { n=Read(),m=Read(); s=n+1,t=n+2; n+=2; for(int i=1; i<=m; i++) { int ki=Read(); int x=Read(),y=x; Addedge(s,x); for(int j=1; j<ki; j++) { x=Read(); Addedge(y,x); y=x; } Addedge(x,t); } printf("%d\n",Dinic()); return 0; }