题目链接:http://poj.org/problem?id=2516
题意:
n个店主 m个供应商 k种货物 给你店主对k种货物的需求及供货商k种货物的囤货量及K种运输费用。
解法:k次费用流,分别求每种货物的费用。源点到供应点建边,店主到汇点建边,费用均为0,容量为1。然后供应点到店主建边,费用为矩阵,容量无穷大即可。
代码:
/*
POJ 2195 Going Home
邻接矩阵形式最小费用最大流
*/
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
//************************************************************
//最小费用最大流算法
//SPFA求最短路
//邻接矩阵形式
//初始化:cap:容量,没有边为0
//cost:耗费,对称形式,没有边的也为0
//c是最小费用
//f是最大流
//*******************************************************
const int MAXN = 500;
const int INF = 0x3fffffff;
int cap[MAXN][MAXN];//容量,没有边为0
int flow[MAXN][MAXN];
//耗费矩阵是对称的,有i到j的费用,则j到i的费用为其相反数
int cost[MAXN][MAXN];//花费
int n;//顶点数目0~n-1
int f;//最大流
int c;//最小费用
int start, End;//源点和汇点
bool vis[MAXN];//在队列标志
int que[MAXN];
int pre[MAXN];
int dist[MAXN];//s-t路径最小耗费
bool SPFA()
{
int front = 0, rear = 0;
for (int u = 0; u <= n; u++)
{
if (u == start)
{
que[rear++] = u;
dist[u] = 0;
vis[u] = true;
}
else
{
dist[u] = INF;
vis[u] = false;
}
}
while (front != rear)
{
int u = que[front++];
vis[u] = false;
if (front >= MAXN)front = 0;
for (int v = 0; v <= n; v++)
{
if (cap[u][v]>flow[u][v] && dist[v]>dist[u] + cost[u][v])
{
dist[v] = dist[u] + cost[u][v];
pre[v] = u;
if (!vis[v])
{
vis[v] = true;
que[rear++] = v;
if (rear >= MAXN)rear = 0;
}
}
}
}
if (dist[End] >= INF)return false;
return true;
}
void minCostMaxflow()
{
memset(flow, 0, sizeof(flow));
c = f = 0;
while (SPFA())
{
int Min = INF;
for (int u = End; u != start; u = pre[u])
Min = min(Min, cap[pre[u]][u] - flow[pre[u]][u]);
for (int u = End; u != start; u = pre[u])
{
flow[pre[u]][u] += Min;
flow[u][pre[u]] -= Min;
}
c += dist[End] * Min;
f += Min;
}
}
//************************************************************
int tmp;
int a[10000][55];
int b[10000][55];
int main()
{
int N, M, K;
while (~scanf("%d%d%d", &N, &M, &K))
{
if (N == 0 && M == 0 && K == 0) break;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
start = 0;
n = N + M+ 2;
End = M + N + 1;
int need = 0;
for (int i = 1; i <= N; i++)
{
for (int k = 1; k <= K;k++)
{
scanf("%d",&a[i][k]);
need += a[i][k];
}
}
for (int i = 1; i <= M; i++)
{
for (int k = 1; k <= K; k++)
{
scanf("%d", &b[i][k]);
}
}
int ans = 0;
int res = 0;
for (int kk = 1; kk <= K; kk++)
{
memset(cap, 0, sizeof(cap));
memset(cost, 0, sizeof(cost));
for (int i = 1; i <= M; i++) //源点向供应点建边
cap[start][i] = b[i][kk];
for(int i = 1; i <= N; i++) //店主向汇点建边
cap[M + i][End] = a[i][kk];
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
{
scanf("%d", &tmp);
cost[j][i + M] = tmp;
cost[i + M][j] = -tmp;
cap[j][i + M] = 1000000;
}
minCostMaxflow();
ans += c;
res += f;
}
if (res == need)
printf("%d\n", ans);
else
printf("-1\n");
}
return 0;
}
版权声明:转载请注明出处。
时间: 2024-10-03 15:01:50