这道题真的很水,如果和前面的几道题比一下的话。
建模很轻松,按照题意无脑建模就行:
1。源点向仓库连一条边,容量为该仓库的货物,费用为0,代表该仓库能提供多少货物
2.每个仓库向每个商店连一条边,容量INF(其实a[i]也可以),费用为Cij
3.每个仓库向汇点连一条边,容量为bi,费用0,代表这个商店接受正好bi的货物。
由于数据sum(a) == sum(b) 就不用考虑别的问题,只需要跑两次费用流,第二次的时候将费用取反就行。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
const int MAXN = 100000;
const int MAXM = 100000;
const int INF = 0x3f3f3f3f;
struct Edge
{
int from,to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;//节点总个数,节点编号从0~N-1
void init(int n)
{
N = n;
tol = 0;
memset(head,-1,sizeof(head));
memset(edge,0,sizeof(edge));
}
void addedge(int u,int v,int cap,int cost)
{
edge[tol].from = u;
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = 0;
edge[tol].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].from = v;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
edge[tol].next = head[v];
head[v] = tol++;
}
bool spfa(int s,int t)
{
queue<int>q;
for(int i = 0; i < N; i++)
{
dis[i] = INF;
vis[i] = false;
pre[i] = -1;
}
dis[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(edge[i].cap > edge[i].flow &&
dis[v] > dis[u] + edge[i].cost )
{
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -1)
return false;
else
return true;
}
//返回的是最大流,cost存的是最小费用
int minCostMaxflow(int s,int t,int &cost)
{
int flow = 0;
cost = 0;
while(spfa(s,t))
{
int Min = INF;
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
edge[i].flow += Min;
edge[i^1].flow -= Min;
cost += edge[i].cost * Min;
}
flow += Min;
}
return flow;
}
void print_all()
{
for(int i = 0; i<tol; i+=2)
{
printf("%d->%d cap = %d flow = %d cost = %d\n",edge[i].from,edge[i].to,edge[i].cap,edge[i].flow,edge[i].cost);
}
}
int a[1001],b[1001];
int c[1001][1001];
int main()
{
int n,m;
scanf("%d%d",&m,&n);
for(int i =1;i<=m;i++)
{
scanf("%d",&a[i]);
}
for(int j = 1;j<=n;j++)
{
scanf("%d",&b[j]);
}
for(int i = 1;i<=m;i++)
{
for(int j = 1;j<=n;j++)
{
scanf("%d",&c[i][j]);
}
}
init(n + m + 2);
for(int i = 1;i<=m;i++)
{
addedge(0,i,a[i],0);
}
for(int i = 1;i<=n;i++)
{
addedge(i + m ,n+m+1,b[i],0);
}
for(int i = 1;i<=m;i++)
{
for(int j = 1;j<=n;j++)
{
addedge(i,j +m,a[i],c[i][j]);
}
}
int cost;
int ans = minCostMaxflow(0,n+m + 1,cost);
printf("%d\n",cost);
init(n + m + 2);
for(int i = 1;i<=m;i++)
{
addedge(0,i,a[i],0);
}
for(int i = 1;i<=n;i++)
{
addedge(i + m ,n+m+1,b[i],0);
}
for(int i = 1;i<=m;i++)
{
for(int j = 1;j<=n;j++)
{
addedge(i,j +m,a[i],-c[i][j]);
}
}
ans = minCostMaxflow(0,n+m+1,cost);
printf("%d\n",-cost);
return 0;
}