题目链接:Minimum Cost
题目大意:有k种流通的物品,有n家店,m个供货商,每家店有k种物品的需求量,每个供货商也有k种物品的供应量,还有k个矩阵,第i行j列表示第j个供应商给第i个店第k种物品的费用。
解题思路:此题的关键思路在于将k个物品分开,每次选取一个物品做一次费用流。源点与供应商相连,容量为供应量,费用为0;汇点与店家相连,容量为需求量,费用为0;供应商与店家根据费用矩阵相连,容量为无穷大。跑k次费用流就可以得到总的最小费用了,因为不同物品的运输不会对彼此造成影响。注意在一开始时如果供应量小于需求量的话是无解的,我们可以做个标记,在连边的时候直接continue掉。
代码如下:
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 2e3 + 15;
int need[55][55], supply[55][55], cost[55][55];
struct Edge {
int to, cap, next, cost;
};
int ecnt, st, ed, ans;
Edge es[30000];
int head[500], dis[500], inq[500], pre[500], flow[500];
void init(){
memset(head, -1, sizeof head);
ecnt = 0;
}
void add_edge(int u, int v, int w, int cap) {
es[ecnt].to = v;
es[ecnt].next = head[u];
es[ecnt].cap = cap;
es[ecnt].cost = w;
head[u] = ecnt++;
}
void add_double(int u, int v, int w, int cap) {
add_edge(u, v, w, cap);
add_edge(v, u, -w, 0);
}
int MCMF() {
while(1) {
memset(dis, 0x3f, sizeof dis);
queue<int> que; que.push(st);
inq[st] = 1; dis[st] = 0;
flow[st] = inf;
while(que.size()) {
int u = que.front();
que.pop(); inq[u] = 0;
for(int i = head[u]; ~i; i = es[i].next) {
Edge& e = es[i];
int v = e.to;
if(e.cap && dis[v] > dis[u] + e.cost) {
dis[v] = dis[u] + e.cost;
flow[v] = min(flow[u], e.cap);
pre[v] = i ^ 1;
if(inq[v]) continue;
inq[v] = 1; que.push(v);
}
}
}
if(dis[ed] == inf) return ans;
ans += flow[ed] * dis[ed];
for(int u = ed; u != st; u = es[pre[u]].to) {
es[pre[u]].cap += flow[ed];
es[pre[u] ^ 1].cap -= flow[ed];
}
}
return -1;
}
inline int read() {
char c = getchar();
while(!isdigit(c)) c = getchar();
int x = 0;
while(isdigit(c)) {
x = x * 10 + c - '0';
c = getchar();
}
return x;
}
int main(){
int n, m, k;
while(scanf("%d%d%d", &n, &m, &k) != EOF) {
if(!n && !m && !k) break;
st = 0, ed = n + m + 1;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= k; j++)
need[i][j] = read();
for(int i = 1; i <= m; i++)
for(int j = 1; j <= k; j++)
supply[i][j] = read();
bool fg = true;
for(int j = 1; j <= k; j++) {
int l = 0, r = 0;
for(int i = 1; i <= n; i++)
l += need[i][j];
for(int i = 1; i <= m; i++)
r += supply[i][j];
if(l > r) {
fg = false;
break;
}
}
int sum = 0;
for(int t = 1; t <= k; t++) {
init(); ans = 0;
for(int i = 1; i <= n; i++) {
add_double(i + m, ed, 0, need[i][t]);
for(int j = 1; j <= m; j++) {
cost[j][i] = read();
add_double(j, i + m, cost[j][i], inf);
}
}
if(!fg) continue;
for(int i = 1; i <= m; i++)
add_double(st, i, 0, supply[i][t]);
MCMF();
sum += ans;
}
if(!fg) puts("-1");
else printf("%d\n", sum);
}
return 0;
}