http://poj.org/problem?id=3281

题意:

有n头牛,F种食物和D种饮料,每头牛都有自己喜欢的食物和饮料,每种食物和饮料只能给一头牛,每头牛需要1食物和1饮料。问最多能满足几头牛的需求。

思路:

POJ 3281 Dining(最大流)-LMLPHP

 #include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
typedef long long ull;
typedef pair<int,int> pll;
const int INF = 0x3f3f3f3f;
const int maxn = + ; struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int w,int f):from(u),to(v),cap(w),flow(f){}
}; struct Dinic
{
int n,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
bool vis[maxn];
int cur[maxn];
int d[maxn]; void init(int n)
{
this->n=n;
for(int i=;i<n;++i) G[i].clear();
edges.clear();
} void AddEdge(int from,int to,int cap)
{
edges.push_back( Edge(from,to,cap,) );
edges.push_back( Edge(to,from,,) );
m=edges.size();
G[from].push_back(m-);
G[to].push_back(m-);
} bool BFS()
{
queue<int> Q;
memset(vis,,sizeof(vis));
vis[s]=true;
d[s]=;
Q.push(s);
while(!Q.empty())
{
int x=Q.front(); Q.pop();
for(int i=;i<G[x].size();++i)
{
Edge& e=edges[G[x][i]];
if(!vis[e.to] && e.cap>e.flow)
{
vis[e.to]=true;
d[e.to]=d[x]+;
Q.push(e.to);
}
}
}
return vis[t];
} int DFS(int x,int a)
{
if(x==t || a==) return a;
int flow=, f;
for(int &i=cur[x];i<G[x].size();++i)
{
Edge &e=edges[G[x][i]];
if(d[e.to]==d[x]+ && (f=DFS(e.to,min(a,e.cap-e.flow) ) )>)
{
e.flow +=f;
edges[G[x][i]^].flow -=f;
flow +=f;
a -=f;
if(a==) break;
}
}
return flow;
} int Maxflow(int s,int t)
{
this->s=s; this->t=t;
int flow=;
while(BFS())
{
memset(cur,,sizeof(cur));
flow +=DFS(s,INF);
}
return flow;
}
}DC; int n,F,D; int main()
{
//freopen("in.txt","r",stdin);
while(~scanf("%d%d%d",&n,&F,&D))
{
int src=, dst=F+D+*n+;
DC.init(dst+); for(int i=;i<=F;i++) DC.AddEdge(src,i,);
for(int i=;i<=D;i++) DC.AddEdge(F+i,dst,); for(int i=;i<=n;i++)
{
DC.AddEdge(F+D+i,F+D+n+i,);
int num1,num2; scanf("%d%d",&num1,&num2);
while(num1--)
{
int x;
scanf("%d",&x);
DC.AddEdge(x,F+D+i,);
}
while(num2--)
{
int x;
scanf("%d",&x);
DC.AddEdge(F+D+n+i,F+x,);
}
}
printf("%d\n",DC.Maxflow(src,dst));
}
return ;
}
05-11 17:28