有F种食物和D种饮料,每种食物或饮料数量有限,且每个人只享用一种食物和一种饮料。现在有n个顾客,每个人都有自己喜欢的食物和饮料,问最多能使几个人同时享用到自己喜欢的食物和饮料。
每个人只用一份food和drink就行了,所以把人拆点,中间连一条容量为1的边。
源点——>food——>人——>人——>drink——>汇点
源点——>food, 容量为食物的存量
food——>人,容量为INF
人——>人,容量为1
人——>drink,容量为INF
drink——>汇点,容量为drink的存量
跑最大流即可。
#include
#include
#include
#include
#include
const int INF = 0x3f3f3f3f;
const int maxn = 200+5;
using namespace std;
int food[maxn], drink[maxn];
char Gf[maxn][maxn], Gd[maxn][maxn];
// 图
struct Edge{
int u, v, cap, flow;
Edge(int a, int b, int c, int d):u(a),v(b),cap(c),flow(d){}
};
vector edges;
vector G[maxn*5];
int dis[maxn*5]; // 分层的编号
int cur[maxn*5]; // 当前弧,重要优化!!!
void init(int a){
for(int i = 0; i < a; ++i) G[i].clear();
edges.clear();
}
void addEdge(int u, int v, int cap){
edges.push_back(Edge(u,v,cap,0));
edges.push_back(Edge(v,u,0,0)); // 反向弧
int m = edges.size();
G[u].push_back(m-2);
G[v].push_back(m-1);
}
// 分层
bool bfs(int s, int t){
memset(dis, -1, sizeof(dis));
dis[s] = 0;
queue Q;
Q.push(s);
while(!Q.empty()){
int x = Q.front(); Q.pop();
for(int i = 0; i < G[x].size(); ++i){
Edge e = edges[G[x][i]];
if(dis[e.v] == -1&&e.cap > e.flow){
dis[e.v] = dis[x] + 1;
Q.push(e.v);
}
}
}
return dis[t] != -1;
}
int dfs(int s, int t, int cur_flow){
if(s == t||cur_flow == 0) return cur_flow;
int ans = 0;
for(int& i = cur[s]; i < G[s].size(); ++i){
int c = G[s][i];
Edge e = edges[c];
if(dis[e.v] == dis[s] + 1&&e.cap > e.flow){
int a2 = min(cur_flow, e.cap-e.flow);
int w = dfs(e.v, t, a2);
edges[c].flow += w;
edges[c^1].flow -= w;
cur_flow -= w;
ans += w;
if(cur_flow <= 0) break;
}
}
return ans;
}
// 最大流
int Dinic(int s, int t){
int ans = 0;
while(bfs(s,t)){
memset(cur, 0, sizeof(cur));
ans += dfs(s,t,INF);
}
return ans;
}
int main()
{
freopen("in.txt","r",stdin);
int N,F,D;
while(scanf("%d%d%d",&N,&F,&D) == 3){
for(int i = 1; i <= F; ++i) scanf("%d",&food[i]);
for(int i = 1; i <= D; ++i) scanf("%d",&drink[i]);
for(int i = 1; i <= N; ++i) scanf("%s",Gf[i]+1);
for(int i = 1; i <= N; ++i) scanf("%s",Gd[i]+1);
// 建图
int s = 0, t = 2*N+F+D+1;
init(2*N+F+D+2);
for(int i = 1; i <= F; ++i) addEdge(s, i, food[i]);
for(int i = 1; i <= N; ++i){
addEdge(F+D+i, F+D+i+N, 1);
for(int j = 1; j <= F; ++j)
if(Gf[i][j] == 'Y') addEdge(j, F+D+i, INF);
for(int j = 1; j <= D; ++j)
if(Gd[i][j] == 'Y') addEdge(F+D+i+N, F+j, INF);
}
for(int i = 1; i <= D; ++i) addEdge(F+i, t, drink[i]);
printf("%d\n", Dinic(s, t));
}
fclose(stdin);
return 0;
}