UVa11613 Acme Corporation(最小费用流)

时间:2023-03-09 17:26:11
UVa11613 Acme Corporation(最小费用流)

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=33452

【思路】

最小费用流。

构图:

1 每个月建立2个点,建立st点

2 相应连边,代价cost为正,盈利cost为负。

跑最小费用流,即当费用大于0时停止最短路增广。即在满足相应流量的限制下不要求流量,只要求费用最小。

【代码】

 #include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#define FOR(a,b,c) for(int a=(b);a<(c);a++)
using namespace std; typedef long long LL ;
const int maxn = +;
const int INF = 1e9; struct Edge{ int u,v,cap,flow,cost;
}; struct MCMF {
int n,m,s,t;
int inq[maxn],a[maxn],d[maxn],p[maxn];
vector<int> G[maxn];
vector<Edge> es; void init(int n) {
this->n=n;
es.clear();
for(int i=;i<n;i++) G[i].clear();
}
void AddEdge(int u,int v,int cap,int cost) {
es.push_back((Edge){u,v,cap,,cost});
es.push_back((Edge){v,u,,,-cost});
m=es.size();
G[u].push_back(m-);
G[v].push_back(m-);
} bool SPFA(int s,int t,int& flow,LL& cost) {
for(int i=;i<n;i++) d[i]=INF;
memset(inq,,sizeof(inq));
d[s]=; inq[s]=; p[s]=; a[s]=INF;
queue<int> q; q.push(s);
while(!q.empty()) {
int u=q.front(); q.pop(); inq[u]=;
for(int i=;i<G[u].size();i++) {
Edge& e=es[G[u][i]];
int v=e.v;
if(e.cap>e.flow && d[v]>d[u]+e.cost) {
d[v]=d[u]+e.cost;
p[v]=G[u][i];
a[v]=min(a[u],e.cap-e.flow); //min(a[u],..)
if(!inq[v]) { inq[v]=; q.push(v);
}
}
}
}
if(d[t]>) return false;
flow+=a[t] , cost+=(LL) a[t]*d[t];
for(int x=t; x!=s; x=es[p[x]].u) {
es[p[x]].flow+=a[t]; es[p[x]^].flow-=a[t];
}
return true;
}
int Mincost(int s,int t,LL& cost) {
int flow=; cost=;
while(SPFA(s,t,flow,cost)) ;
return flow;
}
} mc; int M,I,m,n,p,s,E; int main() {
int T,kase=;
scanf("%d",&T);
while(T--) {
scanf("%d%d",&M,&I);
int start=M*,end=start+;
mc.init(M*+);
FOR(i,,M) {
scanf("%d%d%d%d%d",&m,&n,&p,&s,&E);
mc.AddEdge(start,i,n,m);
mc.AddEdge(M+i,end,s,-p);
FOR(j,,E+)
if(i+j<M) mc.AddEdge(i,M+i+j,INF,I*j);
}
int flow; LL cost;
flow=mc.Mincost(start,end,cost);
printf("Case %d: %lld\n",++kase,-cost);
}
return ;
}