POJ 3281 (最大流+匹配+拆点)

时间:2023-03-09 06:36:26
POJ 3281 (最大流+匹配+拆点)

题目链接:http://poj.org/problem?id=3281

题目大意:有一些牛,一堆食物,一堆饮料。一头牛要吃一份食物喝一份饮料才算满足,而且牛对某些食物和饮料才有好感,问最多有多少头牛是满足的。

解题思路

没有费用的匹配最大流题。

我一开始是这么考虑的,S->牛->食物->饮料->T,cap都是1,啊哈,多简单。

这样是不对的。因为牛比较挑剔,假设牛1喜欢食物1,而不喜欢饮料1,那么食物1和饮料1之间连不连边呢?

不连吧,其它牛怎么办?

连吧,牛1怎么办?

果断不能这么建图。于是改成S->食物->牛->饮料->T,这样就解决了模棱两可的食物与饮料之间的联系。

但是新的问题又来了,假设有食物1->牛1->饮料1,那么又会有食物2->牛1->饮料2,这样一头牛就吞了多份食物和饮料。

解决方案是拆点,把牛插成牛->牛',cap=1,这样一头牛只会被用一次了。

最终的建图方案:S->食物->牛->牛’->饮料->T。

#include "cstdio"
#include "vector"
#include "cstring"
#include "queue"
using namespace std;
#define maxn 405
#define inf 100000000
struct Edge
{
int from,to,cap,flow;
Edge(int FROM,int TO,int CAP,int FLOW):from(FROM),to(TO),cap(CAP),flow(FLOW) {}
};
int d[maxn],p[maxn],gap[maxn],cur[maxn];
bool vis[maxn];
vector<int> G[maxn],food[],drink[];
vector<Edge> edges;
void addedge(int from,int to,int cap)
{
edges.push_back(Edge(from,to,cap,));
edges.push_back(Edge(to,from,,));
int m=edges.size();
G[from].push_back(m-);
G[to].push_back(m-);
}
void bfs(int s,int t)
{
memset(vis,false,sizeof(vis));
memset(d,,sizeof(d));
memset(p,,sizeof(p));
d[t]=;vis[t]=true;
queue<int> Q;Q.push(t);
while(!Q.empty())
{
int u=Q.front();Q.pop();
for(int v=;v<G[u].size();v++)
{
Edge e=edges[G[u][v]^];
if(!vis[e.from]&&e.cap>e.flow)
{
vis[e.from]=true;
d[e.from]=d[u]+;
Q.push(e.from);
}
}
}
}
int augment(int s,int t)
{
int x=t,a=inf;
while(x!=s)
{
Edge e=edges[p[x]];
a=min(a,e.cap-e.flow);
x=e.from;
}
x=t;
while(x!=s)
{
edges[p[x]].flow+=a;
edges[p[x]^].flow-=a;
x=edges[p[x]].from;
}
return a;
}
int maxflow(int s,int t)
{
int flow=,u=s;
bfs(s,t);
memset(gap,,sizeof(gap));
memset(cur,,sizeof(cur));
for(int i=;i<=t;i++) gap[d[i]]++;
while(d[s]<t+)
{
if(u==t)
{
flow+=augment(s,t);
u=s;
}
bool flag=false;
for(int v=cur[u];v<G[u].size();v++) //Advance
{
Edge e=edges[G[u][v]];
if(e.cap>e.flow&&d[u]==d[e.to]+)
{
flag=true;
p[e.to]=G[u][v];
cur[u]=v;
u=e.to;
break;
}
}
if(!flag) //Retreat
{
int m=t+;
for(int v=;v<G[u].size();v++)
{
Edge e=edges[G[u][v]];
if(e.cap>e.flow) m=min(m,d[e.to]);
}
if(--gap[d[u]]==) break;
gap[d[u]=m+]++;
cur[u]=;
if(u!=s) u=edges[p[u]].from;
}
}
return flow;
}
int main()
{
int N,M,K,f,d,t;
while(scanf("%d%d%d",&N,&M,&K)!=EOF)
{
for(int i=;i<=M;i++) addedge(,i,); //S-food
for(int i=;i<=K;i++) addedge(i+M+N*,K+M+N*+,); //drink-T
for(int i=;i<=N;i++)
{
addedge(i+M,i+M+N,); //cow-cow'
scanf("%d%d",&f,&d);
for(int j=; j<=f; j++)
{
scanf("%d",&t);
addedge(t,i+M,); //food-cow
}
for(int j=; j<=d; j++)
{
scanf("%d",&t);
addedge(i+M+N,t+M+*N,); //cow'-drink
}
}
printf("%d\n",maxflow(,*N+M+K+));
}
}
13456393 neopenx 3281 Accepted 320K 16MS C++ 3222B 2014-09-19 00:28:49