按照题意建模就行了。
#include<bits/stdc++.h> #define naive 0 #define inf 1000000007 using namespace std; int n,m,T,a[100][100],head[1005],tot,qwq,level[1005],ans,s,t; struct Edge{int u,v,f,next;}G[100010]; inline void addedge(int u,int v,int f){ G[tot].u=u;G[tot].v=v;G[tot].f=f;G[tot].next=head[u];head[u]=tot++; G[tot].u=v;G[tot].v=u;G[tot].f=0;G[tot].next=head[v];head[v]=tot++; } inline bool bfs(){ memset(level,naive,sizeof(level));queue<int>q; q.push(s);level[s]=1; while(!q.empty()){ int u=q.front();q.pop(); if(u==t)return 1; for(int i=head[u];~i;i=G[i].next){ int v=G[i].v,f=G[i].f; if(f&&!level[v])level[v]=level[u]+1,q.push(v); } } return naive; } int dfs(int u,int maxf,int t){ if(u==t)return maxf;int rat=0; for(int i=head[u];~i&&rat<maxf;i=G[i].next){ int v=G[i].v,f=G[i].f; if(f&&level[v]==level[u]+1){ f=dfs(v,min(f,maxf-rat),t); rat+=f;G[i].f-=f;G[i^1].f+=f; } } if(!rat)level[u]=inf; return rat; } inline int dinic(){ int ans=0;while(bfs())ans+=dfs(s,inf,t); return ans; } inline int read(){ int f=1,x=naive;char ch; do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9'); do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9'); return f*x; } int main(){ int T=read(); while(T--){t=1001; n=read();m=read();memset(head,-1,sizeof(head));tot=naive;memset(a,0,sizeof(a)); ans=0; for(int i=1;i<=n;i++){int x=read();while(x--)a[i][read()]++;} for(int i=1;i<=m;i++)addedge(s,i,a[1][i]); for(int i=2;i<=n;i++)for(int j=1;j<=m;j++) if(a[i][j]>1)addedge(i+m,j,a[i][j]-1); for(int i=2;i<=n;i++)for(int j=1;j<=m;j++)if(!a[i][j])addedge(j,i+m,1); for(int i=1;i<=m;i++)addedge(i,t,1); ans=dinic();printf("Case #%d: %d ",++qwq,ans); } }