一开始打算把所有的物品放一齐,一齐跑个最小费用最大流KO它。结果点越来越多,边也随之增加,下标也开始算不清楚了。。。就算建出来估计也会给我TLE掉。
题意:
有m个供应站,n个店面,k种物品。
每个供应站都供应一定量的k种物品,每个店面都需求一定量的k种物品。
每种物品从某个供应站运送到某个店面的费用不均相同。
问:找出最小费用的方案。如果不能满足所有店面的需求,输出-1;否则输出最小费用。
思路:
输入完成后判断是否能满足所有店面的需求。若能满足则继续。
分组计算,每个物品建一次图,跑一次最小费用流。最终把所有的费用加起来即是本题答案。
AC代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define debug cout<<"debug"<<endl;
const int MAXN = 55;
const int MAXM = 55;
const int MAXK = 55;
const int MAXEDGE = 1e5+5;
const int INF = 0x3f3f3f3f;
const int GE = 105;
int n, m, k;
int an[MAXN][MAXK];
int am[MAXM][MAXK];
int ak[MAXK][MAXN][MAXM];
struct CEdge
{
int from, to, cap, flow, cost, next;
}edge[MAXEDGE], backup[MAXEDGE];
struct CMCMF
{
int s, t, pp;
int head[GE], d[GE], a[GE], p[GE];
bool inq[GE];
int sumn[MAXN], summ[MAXM];
CMCMF(int ss, int tt)
{
s = ss, t = tt;
pp = 0;
memset(sumn, 0, sizeof(sumn));
memset(summ, 0, sizeof(summ));
//memset(head, -1, sizeof(head));
}
void addEdge(int from, int to, int cap, int cost)
{
edge[pp] = (CEdge){from, to, cap, 0, cost, head[from]};
head[from] = pp++;
edge[pp] = (CEdge){to, from, 0, 0, -cost, head[to]};
head[to] = pp++;
}
bool input(int &cost, int &flow)
{
//build
for(int i = 1;i <= n; i++)
{
for(int j = 1;j <= k; j++)
{
scanf("%d",&an[i][j]);
sumn[j] += an[i][j];
}
}
for(int i = 1;i <= m; i++)
{
for(int j = 1;j <= k; j++)
{
scanf("%d",&am[i][j]);
summ[j] += am[i][j];
}
}
for(int i = 1;i <= k ;i++)
{
for(int j = 1;j <= n; j++)
{
for(int z = 1;z <= m; z++)
{
scanf("%d",&ak[i][j][z]);
}
}
}
for(int i = 1;i <= k ; i++)
if(summ[i] < sumn[i]) return false;
//build graph;
for(int c = 1;c <= k; c++)
{
memset(head, -1, sizeof(head));
pp = 0;
for(int i = 1;i <= m; i++)
addEdge(s, i, am[i][c], 0);
for(int i = 1;i <= n; i++)
addEdge(m+i, t, an[i][c], 0);
//
for(int i = 1;i <= m; i++)
{
for(int j = 1;j <= n; j++)
{
addEdge(i, m+j, INF, ak[c][j][i]);
}
}
while(bellmanFord(flow, cost));
}
return true;
}
bool bellmanFord(int &flow, int &cost)
{
memset(inq, false, sizeof(inq));
memset(d, INF, sizeof(d));
queue <int> q;
q.push(s), inq[s] = true;
d[s] = 0, a[s] = INF, p[s] = -1;
while(!q.empty())
{
int u = q.front();
q.pop(), inq[u] = false;
int next = head[u];
while(next != -1)
{
CEdge &e = edge[next];
if(e.cap > e.flow && d[e.to] > d[u] + e.cost)
{
d[e.to] = d[u] + e.cost;
a[e.to] = min(a[u], e.cap - e.flow);
p[e.to] = next;
if(!inq[e.to]) inq[e.to] = true, q.push(e.to);
}
next = e.next;
}
}
if(d[t] == INF) return false;
cost += d[t] * a[t];
flow += a[t];
int u = t;
while(u != s)
{
edge[p[u]].flow += a[t];
edge[p[u]^1].flow -= a[t];
u = edge[p[u]].from;
}
return true;
}
};
int main()
{
while(scanf("%d%d%d",&n, &m, &k), n&&m&&k)
{
int s = 0, t = m+n+1;
CMCMF mcmf(s, t);
int cost = 0, flow = 0;
if(!mcmf.input(cost, flow))
puts("-1");
else
cout<<cost<<endl;
}
return 0;
}