考虑到食物和饮料的两种限制,构图时把人放在中间。人需要拆点,否则可能有多种组合通过一个人流过去。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n,f,d;
const int maxnode =2000 + 5;
const int maxedge = 200000 + 5;
const int oo = 1000000000;
int node, src, dest, nedge;
int head[maxnode], point[maxedge], next1[maxedge], flow[maxedge], capa[maxedge];//point[x]==y表示第x条边连接y,head,next为邻接表,flow[x]表示x边的动态值,capa[x]表示x边的初始值
int dist[maxnode], Q[maxnode], work[maxnode];//dist[i]表示i点的等级
void init(int _node, int _src, int _dest){//初始化,node表示点的个数,src表示起点,dest表示终点
node = _node;
src = _src;
dest = _dest;
for (int i = 0; i < node; i++) head[i] = -1;
nedge = 0;
}
void addedge(int u, int v, int c1, int c2){//增加一条u到v流量为c1,v到u流量为c2的两条边
point[nedge] = v, capa[nedge] = c1, flow[nedge] = 0, next1[nedge] = head[u], head[u] = (nedge++);
point[nedge] = u, capa[nedge] = c2, flow[nedge] = 0, next1[nedge] = head[v], head[v] = (nedge++);
}
bool dinic_bfs(){
memset(dist, 255, sizeof (dist));
dist[src] = 0;
int sizeQ = 0;
Q[sizeQ++] = src;
for (int cl = 0; cl < sizeQ; cl++)
for (int k = Q[cl], i = head[k]; i >= 0; i = next1[i])
if (flow[i] < capa[i] && dist[point[i]] < 0){
dist[point[i]] = dist[k] + 1;
Q[sizeQ++] = point[i];
}
return dist[dest] >= 0;
}
int dinic_dfs(int x, int exp){
if (x == dest) return exp;
for (int &i = work[x]; i >= 0; i = next1[i]){
int v = point[i], tmp;
if (flow[i] < capa[i] && dist[v] == dist[x] + 1 && (tmp = dinic_dfs(v, min(exp, capa[i] - flow[i]))) > 0){
flow[i] += tmp;
flow[i^1] -= tmp;
return tmp;
}
}
return 0;
}
int dinic_flow(){
int result = 0;
while (dinic_bfs()){
for (int i = 0; i < node; i++) work[i] = head[i];
while (1){
int delta = dinic_dfs(src, oo);
if (delta == 0) break;
result += delta;
}
}
return result;
}
//建图前,运行一遍init();
//加边时,运行addedge(a,b,c,0),表示点a到b流量为c的边建成(注意点序号要从0开始)
//求解最大流运行dinic_flow(),返回值即为答案
int main()
{
while(scanf("%d%d%d",&n,&f,&d)!=EOF)
{
int i,j;
int ta,tb,ans;
char ts[205];
init(2+n+n+f+d,0,n*2+f+d+1);
for(i=1;i<=f;i++)
{
scanf("%d",&ta);
addedge(0,i,ta,0);
}
for(i=1;i<=d;i++)
{
scanf("%d",&ta);
addedge(f+n*2+i,f+n*2+d+1,ta,0);
}
for(i=1;i<=n;i++)
addedge(f+i,f+n+i,1,0);
for(i=1;i<=n;i++)
{
scanf("%s",ts);
for(j=0;j<f;j++)
{
if(ts[j]=='Y')
{
addedge(j+1,f+i,1,0);
}
}
}
for(i=1;i<=n;i++)
{
scanf("%s",ts);
for(j=0;j<d;j++)
{
if(ts[j]=='Y')
{
addedge(f+n+i,f+n*2+1+j,1,0);
}
}
}
ans=dinic_flow();
printf("%d\n",ans);
}
return 0;
}