AC日记——Collectors Problem uva 10779
思路:
最大流;
s向所有的贴纸的种类连边,流量为Bob拥有的数量;
然后,Bob的朋友如果没有这种贴纸,则这种贴纸向bob的朋友连边,容量1;
如果bob的朋友的贴纸很多大于1,向该贴纸的种类连边,容量数量-1;
所有贴纸的种类向t连边,容量1;
代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define maxn 1005 #define maxque 100005 #define INF 0x7fffffff int V[maxque],F[maxque],cnt,s,t,num[maxn][maxn]; int n,m,head[maxn],que[maxque],E[maxque],ans,deep[maxn]; inline void in(int &now) { char Cget=getchar();now=0; while(Cget>'9'||Cget<'0') Cget=getchar(); while(Cget>='0'&&Cget<='9') { now=now*10+Cget-'0'; Cget=getchar(); } } inline void edge_add(int u,int v,int f) { E[++cnt]=head[u],V[cnt]=v,F[cnt]=f,head[u]=cnt; E[++cnt]=head[v],V[cnt]=u,F[cnt]=0,head[v]=cnt; } inline bool bfs() { for(int i=s;i<=t;i++) deep[i]=-1; int h=0,tail=1,now;que[h]=s,deep[s]=0; while(h<tail) { now=que[h++]; for(int i=head[now];i;i=E[i]) { if(deep[V[i]]<0&&F[i]>0) { deep[V[i]]=deep[now]+1; if(V[i]==t) return true; que[tail++]=V[i]; } } } return false; } inline int flowing(int now,int flow) { if(now==t||flow<=0) return flow; int oldflow=0; for(int i=head[now];i;i=E[i]) { if(F[i]&&deep[V[i]]==deep[now]+1) { int pos=flowing(V[i],min(flow,F[i])); flow-=pos,oldflow+=pos,F[i]-=pos,F[i^1]+=pos; if(flow==0) return oldflow; } } if(oldflow==0) deep[now]=-1; return oldflow; } int main() { int T;in(T); for(int v=1;v<=T;v++) { cnt=1,in(n),in(m),s=0,t=n+m+1,ans=0;int pos,num_; memset(num,0,sizeof(num)),memset(head,0,sizeof(head)); for(int i=1;i<=n;i++) { in(num_); for(int j=1;j<=num_;j++) in(pos),num[i][pos]++; } for(int i=1;i<=m;i++) { edge_add(n+i,t,1); if(num[1][i]) edge_add(s,n+i,num[1][i]); } for(int i=2;i<=n;i++) { for(int j=1;j<=m;j++) { if(num[i][j]) { if(num[i][j]>1) edge_add(i,j+n,num[i][j]-1); } else edge_add(j+n,i,1); } } while(bfs()) ans+=flowing(s,INF); printf("Case #%d: %d\n",v,ans); } return 0; }