题目大意:
你要给N个老板供应K种货物,你有M格仓库,并且知道每一种货物的存货,但是同一种货物从不同的仓库供应不同的老板会消耗不同的费用。
(多组测试数据)
思路:对于每个给定的情况,
我把K种货物分开求解,构图 S --> M --> N --> T
S 表示构造出来的源点,S --> 每个M 有一条容量为货物存量,费用为0 的边
M 表示M个仓库, 每个M --> 每个N 有一条容量为货物存量, 费用为运输费用的边
N 表示N个老板, 每个M --> T 有一条容量为货物需求量, 费用为0 的边
T 表示汇点
代码如下:
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
struct rec
{
int u, c, f, v, e;
};
int const maxn = 55;
int const maxx = 1000000000;
int n, m, K, S, T, tot, point, minicost;
int cost[maxn][maxn][maxn], need[maxn][maxn], store[maxn][maxn], w[maxn*maxn], head[maxn*5], dis[maxn*5], path[maxn*5], fa[maxn*5];
rec gf[2*maxn*maxn];
bool vis[maxn*5];
void add_adge(int u1, int v1, int ct, int price)
{
gf[tot].u = v1; gf[tot].v = price; gf[tot].f = 0; gf[tot].c = ct; gf[tot].e = head[u1]; head[u1] = tot++;
gf[tot].u = u1; gf[tot].v = -price; gf[tot].f = 0; gf[tot].c = 0; gf[tot].e = head[v1]; head[v1] = tot++;
}
bool find_shortest_path()
{
for (int i = 0; i <= point; ++i)
dis[i] = maxx;
int l=0, r=1, t;
w[0] = S;
dis[S] = 0;
memset(vis, false, sizeof(vis));
while (l < r)
{
t = head[w[l]];
while (t != -1)
{
if (gf[t].c > gf[t].f && gf[t].v+dis[w[l]] < dis[gf[t].u])
{
dis[gf[t].u] = gf[t].v+dis[w[l]];
path[gf[t].u] = t;
fa[gf[t].u] = w[l];
if (!vis[gf[t].u])
{
vis[gf[t].u] = true;
w[r++] = gf[t].u;
}
}
t = gf[t].e;
}
vis[w[l++]] = false;
}
if (dis[T] == maxx) return 0;
int min = maxx;
for (l = T; l != S; l = fa[l])
if (gf[path[l]].c - gf[path[l]].f < min) min = gf[path[l]].c - gf[path[l]].f;
for (l = T; l != S; l = fa[l])
{
minicost += min*gf[path[l]].v;
gf[path[l]].f += min;
gf[path[l]^1].f -= min;
}
return 1;
}
bool readd()
{
cin >> n >> m >> K;
if (n == 0 && m == 0 && K == 0) return 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < K; ++j)
cin >> need[j][i];
for (int i = 0; i < m; ++i)
for (int j = 0; j < K; ++j)
cin >> store[j][i];
for (int l = 0; l < K; ++l)
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
cin >> cost[l][j][i];
return 1;
}
bool if_valid()
{
int sum;
for (int i = 0; i < K; ++i)
{
sum = 0;
for (int j = 0; j < m; sum += store[i][j++]);
for (int j = 0; j < n; sum -= need[i][j++]);
if (sum < 0) return 0;
}
return 1;
}
void make_graph(int p)
{
S = 0; T = m+n+1;
point = m+n+1;
memset(head, -1, sizeof(head));
tot = 0;
for (int i = 1; i <= m; ++i)
add_adge(S, i, store[p][i-1], 0);
for (int i = 1; i <= n; ++i)
add_adge(i+m, T, need[p][i-1], 0);
for (int i = 1; i <= m; ++i)
for (int j = 1; j <= n; ++j)
add_adge(i, j+m, store[p][i-1], cost[p][i-1][j-1]);
}
int main()
{
while (readd())
{
if (if_valid())
{
minicost = 0;
for (int oi = 0; oi < K; ++oi)
{
make_graph(oi);
while (find_shortest_path());
}
cout << minicost << endl;
}
else cout << -1 << endl;
}
}