POJ-2516-Minimum Cost
N Customers, M suppliers, K types of goods, provide some supply and demand relationships, and find the minimum price when the conditions are met
The minimum cost and the maximum flow. You can calculate the minimum cost for each of the k types of goods at a time and add them together.
[Cpp]
# Include <stdio. h>
# Include <string. h>
# Include <math. h>
# Define maxn300
# Define INF 0x7fffffff
Int min (int x, int y)
{
Return x <y? X: y;
}
Int map [maxn] [maxn], vis [maxn], cap [maxn] [maxn], dis [maxn];
Int que [maxn], pre [maxn];
Int num, ans;
Int SPFA ()
{
Int I, k;
Int head, tail;
Memset (vis, 0, sizeof (vis ));
For (I = 0; I <= num; I ++)
Dis [I] = INF;
Dis [0] = 0;
Vis [0] = 1;
Head = tail = 0;
Que [0] = 0;
Tail ++;
While (head <tail)
{
K = que [head];
Vis [k] = 0;
For (I = 0; I <= num; I ++)
{
If (cap [k] [I] & dis [I]> dis [k] + map [k] [I])
{
Dis [I] = dis [k] + map [k] [I];
Pre [I] = k;
If (! Vis [I])
{
Vis [I] = 1;
Que [tail ++] = I;
}
}
}
Head ++;
}
If (dis [num] <INF)
Return 1;
Return 0;
}
Void end ()
{
Int I, sum = INF;
For (I = num; I! = 0; I = pre [I])
Sum = min (sum, cap [pre [I] [I]);
For (I = num; I! = 0; I = pre [I])
{
Cap [pre [I] [I]-= sum;
Cap [I] [pre [I] + = sum;
Ans + = map [pre [I] [I] * sum;
}
}
Int main ()
{
Int N, M, K, I, j, k;
Int need [maxn] [maxn], needk [maxn];
Int have [maxn] [maxn], havek [maxn];
Int flag;
While (scanf ("% d", & N, & M, & K), N)
{
Memset (needk, 0, sizeof (needk ));
For (I = 1; I <= N; I ++) // customer
For (j = 1; j <= K; j ++)
{
Scanf ("% d", & need [I] [j]);
Needk [j] + = need [I] [j];
}
Memset (havek, 0, sizeof (havek ));
For (I = 1; I <= M; I ++) // supplier
For (j = 1; j <= K; j ++)
{
Scanf ("% d", & have [I] [j]);
Havek [j] + = have [I] [j];
}
Flag = 1;
For (I = 1; I <= K; I ++)
If (needk [I]> havek [I])
{
Flag = 0;
Break;
}
Ans = 0;
Num = N + M + 1;
For (k = 1; k <= K; k ++) // process each cargo
{
Memset (cap, 0, sizeof (cap ));
Memset (map, 0, sizeof (map ));
For (I = 1; I <= N; I ++)
For (j = 1; j <= M; j ++)
{
Scanf ("% d", & map [j] [M + I]);
Map [M + I] [j] =-map [j] [M + I];
Cap [j] [M + I] = have [j] [k];
Cap [M + I] [j] = 0;
}
If (! Flag)
Continue;
For (I = 1; I <= M; I ++) // edge creation from the source point to the supplier
{
Cap [0] [I] = have [I] [k];
Map [0] [I] = map [I] [0] = 0;
}
For (I = 1; I <= N; I ++) // The customer builds an edge from the sink.
{
Cap [M + I] [num] = need [I] [k];
Map [M + I] [num] = map [num] [M + I] = 0;
}
While (SPFA ())
End ();
}
If (flag)
Printf ("% d \ n", ans );
Else
Printf ("-1 \ n ");
}
Return 0;
}