思路
这个图真的建的太恶心了 题意就读了好长时间 由于点数太多 所以我们考虑将每种货物分别求一次最大流最小费用 然后最后加起来判断最大流是否满足题意
部分数据(隔壁博客偷来的555)
input
1 3 3
1 1 1
0 1 1
1 2 2
1 0 1
1 2 3
1 1 1
2 1 1
1 1 1
3
2
20
2 4 3
0 2 3
2 3 4
1 0 2
1 0 3
0 2 4
2 3 0
2 3 1 2
1 2 3 1
1 1 2 3
2 1 3 1
2 2 3 1
2 3 4 1
2 2 1
1 1 1 1
1 2 2 100
2 4 5
2 1 2 2 2
1 1 1 2 1
2 2 2 2 2
2 1 2 1 1
2 2 2 2 1
1 2 2 2 1
1 1 6 7
5 5 2 9
4 6 6 9
9 1 9 1
7 4 1 7
4 4 7 3
5 4 7 7
9 1 3 8
8 8 2 7
1 4 7 1
1 2 3
1 1 2
2 2 1
2 1 1
7 4
4 1
7 3
0 0 0
output:
4
-1
27
4
38
15
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 5010, M = 500010, INF = 1e8;
int n, m, K, S, T;
int h[N], e[M], ne[M], f[M], w[M], idx;
int d[N], incf[N], pre[N];
bool st[N];
int need[N][N], stock[N][N];
int Cost, Flow;
queue<int> q;
void init()
{
memset(h, -1, sizeof h);
idx = 0;
}
void add(int a, int b, int c, int d)
{
e[idx] = b, ne[idx] = h[a], w[idx] = d, f[idx] = c, h[a] = idx ++ ;
e[idx] = a, ne[idx] = h[b], w[idx] = -d, f[idx] = 0, h[b] = idx ++ ;
}
bool spfa()
{
memset(incf, 0, sizeof incf);
memset(d, 0x3f, sizeof d);
q.push(S), d[S] = 0, incf[S] = INF;
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int ver = e[i];
if (f[i] && d[ver] > d[t] + w[i])
{
d[ver] = d[t] + w[i];
pre[ver] = i;
incf[ver] = min(f[i], incf[t]);
if (!st[ver])
{
q.push(ver);
st[ver] = true;
}
}
}
}
return incf[T] > 0;
}
int EK()
{
Cost = 0, Flow = 0;
while (spfa())
{
int t = incf[T];
Cost += t * d[T], Flow += t;
for (int i = T; i != S; i = e[pre[i] ^ 1])
{
f[pre[i]] -= t;
f[pre[i] ^ 1] += t;
}
}
}
int main()
{
while (scanf("%d%d%d", &n, &m, &K), n || m || K)
{
int cost = 0, flow = 0, sum = 0;;
S = 0, T = N - 1;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= K; j ++ )
{
scanf("%d", &need[i][j]);
sum += need[i][j];
}
for (int i = 1; i <= m; i ++ )
for (int j = 1; j <= K; j ++ )
scanf("%d", &stock[i][j]);
for (int k = 1; k <= K; k ++ )
{
init();
for (int i = 1; i <= n; i ++ ) add(i + m, T, need[i][k], 0);
for (int i = 1; i <= m; i ++ ) add(S, i, stock[i][k], 0);
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
{
int c;
scanf("%d", &c);
add(j, i + m, stock[j][k], c);
}
EK();
cost += Cost, flow += Flow;
}
if (flow == sum) printf("%d\n", cost);
else puts("-1");
}
return 0;
}