#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<cmath>
using namespace std;
const int N=220;
const int INF=0X3F3F3F3F;
int n,m,k;//n表示商家,m表示供应商(0-50),k表示种类(0-3)
int need[N][N];//需求
int provide[N][N];//供应
int volume[N];//表示第k个品的所有的提供数目
struct Edge {
int from, to, cap, flow, cost;
};
struct MCMF {
int n, m;
vector<Edge> edges;
vector<int> G[N];
int d[N], inq[N], p[N], a[N];
void init(int n) {
this->n = n;
for (int i = 0; i <= n; ++i) G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int cap, int cost) {
edges.push_back(Edge{from, to, cap, 0, cost});
edges.push_back(Edge{to, from, 0, 0, -cost});
m = edges.size();
G[from].push_back(m-2); G[to].push_back(m-1);
}
bool spfa(int s, int t, int &flow, int &cost) {
//M(inq, 0); M(d, INF);
memset(inq,0,sizeof(inq));
memset(d,INF,sizeof(d));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> q;
q.push(s);
while (!q.empty()) {
int x = q.front(); q.pop();
inq[x] = 0;
for (int i = 0; i < G[x].size(); ++i) {
Edge &e = edges[G[x][i]];
if (d[e.to] > d[x] + e.cost && e.cap > e.flow) {
d[e.to] = d[x] + e.cost;
p[e.to] = G[x][i];
a[e.to] = min(a[x], e.cap-e.flow);
if (inq[e.to]) continue;
q.push(e.to); inq[e.to] = 1;
}
}
}
if (d[t] == INF) return false;
flow += a[t];
cost += d[t] * a[t];
int u = t;
while (u != s) {
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
u = edges[p[u]].from;
}
return true;
}
int Mincost(int s, int t) {
int flow = 0, cost = 0;
while (spfa(s, t, flow, cost));
return cost;
}
}solver;
int main(){
while(cin>>n>>m>>k&&(n||m||k)){
memset(volume,0,sizeof(volume));
for(int i=1;i<=n;i++){
for(int j=1;j<=k;j++){
cin>>need[i][j];
}
}
for(int i=1;i<=m;i++){
for(int j=1;j<=k;j++){
cin>>provide[i][j];
volume[j]+=provide[i][j];
}
}
bool flag=true;
int cost=0;
for(int s=1;s<=k;s++){
int s1=0,t=n+m+1;
solver.init(n+m+1);
int volume1=0;
for(int i=1;i<=n;i++){
solver.AddEdge(s1,i,need[i][s],0);
volume1+=need[i][s];
}
if(volume1>volume[s])
flag=false;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
int co;
cin>>co;
solver.AddEdge(i,n+j,INF,co);
}
}
for(int i=1;i<=m;i++){
solver.AddEdge(i+n,t,provide[i][s],0);
}
if(flag){
cost+=solver.Mincost(s1,t);
}
}
if(flag)
cout<<cost<<endl;
else
{
cout<<-1<<endl;
}
}
return 0;
}
原文:https://www.cnblogs.com/GarrettWale/p/11438319.html