洛谷P2891 [USACO07OPEN]吃饭Dining:
https://www.luogu.org/problemnew/show/P2891
n头牛f个食物d个饮料 求有多少头牛同时能享受到食物和饮料
(其实我第一反应是二分图匹配 [而且题目又是牛!不就是公牛配母牛吗!])
好吧它既要满足有肉吃还要满足有水喝(比机房日子好多了学校的饭真的不好吃quq)
网络流?
好吧这只是一个建边问题owo
给个样例的图:
4 3 3
2 2 1 2 3 1
2 2 2 3 1 2
2 2 1 3 1 2
2 1 1 3 3
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct node
{
int x,y,c,other,next;
}a[5100];
int last[5100],len;
int dep[5100];
int list[5100];
int head,tail,st,ed;
void build(int x,int y,int c)
{
int k1,k2;
len++;k1=len;
a[len].x=x;a[len].y=y;a[len].c=c;a[len].next=last[x];last[x]=len;
len++;k2=len;
a[len].x=y;a[len].y=x;a[len].c=0;a[len].next=last[y];last[y]=len;
a[k1].other=k2;a[k2].other=k1;
}
int bfs()
{
memset(dep,0,sizeof(dep));
head=tail=1;
list[1]=st;dep[st]=1;
while (head<=tail)
{
int x=list[head];
for (int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if (a[k].c>0&&dep[y]==0)
{
list[++tail]=y;
dep[y]=dep[x]+1;
}
}
head++;
}
if (dep[ed]==0) return 0;
else return 1;
}
int dfs(int x,int flow)
{
if (x==ed) return flow;
int tot=0,sum=0;
for (int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if (dep[y]==dep[x]+1&&a[k].c>0&&tot<flow)
{
sum=dfs(y,min(a[k].c,flow-tot));
tot+=sum;
a[k].c-=sum;a[a[k].other].c+=sum;
}
}
if (tot==0) dep[x]=0;
return tot;
}
int main()
{
/*
st-food-cow-cow-drink-ed
*/
int f,d,n;
scanf("%d%d%d",&n,&f,&d);
st=1;ed=1+2*n+f+d+1;
for (int i=1;i<=f;i++) build(st,i+1,1);
for (int i=1;i<=n;i++)
{
int fi,di,x;
scanf("%d%d",&fi,&di);
for (int j=1;j<=fi;j++)
{
scanf("%d",&x);
build(1+x,1+f+i,1);//food-cow
}
build(1+f+i,1+f+n+i,1);
for (int j=1;j<=di;j++)
{
scanf("%d",&x);
build(1+f+n+i,1+f+2*n+x,1);//cow-drink
}
}
for (int i=1;i<=d;i++) build(1+f+2*n+i,ed,1);
int ans=0,s=0;
while (bfs())
{
ans+=dfs(st,999999999);
}
printf("%d\n",ans);
return 0;
}