费用流+动态加边

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn=520130;
const int INF=987654321;
struct Edge{
int from,to,cap,flow,cost;
};
int P[maxn],Time[45][110],tot=0,cnt[110];
vector<Edge>edges;
vector<int>G[maxn];
int n,m,s,t;
int dist[maxn],a[maxn],p[maxn];
bool inQ[maxn];
void Addedge(int from,int to,int cap,int cost){
Edge e;
e.from=from,e.to=to,e.cap=cap,e.flow=0,e.cost=cost;
edges.push_back(e);
e.from=to,e.to=from,e.cap=0,e.flow=0,e.cost=-cost;
edges.push_back(e);
int M=edges.size();
G[from].push_back(M-2);
G[to].push_back(M-1);
}
bool spfa(int &New,int &Maxflow,int &Mincost){
for(int i=s;i<=t;i++)dist[i]=INF;
memset(inQ,0,sizeof(inQ));
dist[s]=0,inQ[s]=1,p[s]=0,a[s]=INF;
queue<int>Q;
Q.push(s);
while(!Q.empty())
{ int u=Q.front();Q.pop();
inQ[u]=0;
for(int i=0;i<G[u].size();i++)
{ Edge& e=edges[G[u][i]];
if(e.cap>e.flow &&dist[e.to]>dist[u]+e.cost)
{ dist[e.to]=dist[u]+e.cost;
p[e.to]=G[u][i];
a[e.to]=min(a[u],e.cap-e.flow);
if(!inQ[e.to]){inQ[e.to]=1;Q.push(e.to);}
}
}
}
if(dist[t]==INF)return false;
Maxflow+=a[t];
Mincost+=dist[t]*a[t];
int u=t;
New=(edges[p[u]].from-n)/tot+1;
//cout<<"New: "<<New<<endl;
cnt[New]++;
while(u!=s)
{ edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
u=edges[p[u]].from;
}
return true;
}
int mincost(){
int Maxflow=0,Mincost=0,New;
while(spfa(New,Maxflow,Mincost))
{ for(int i=1;i<=n;i++)
Addedge(i,n+(New-1)*tot+cnt[New],1,Time[i][New]*cnt[New]);
Addedge(n+(New-1)*tot+cnt[New],t,1,0);
}
return Mincost;
}
void read_data(){
scanf("%d%d",&n,&m);

for(int i=1;i<=n;i++)
{ scanf("%d",&P[i]);
tot+=P[i];
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&Time[i][j]);

}
void Build_graph(){
s=0;t=n+m*tot+1;
//cout<<"tot: "<<tot<<endl;
for(int i=1;i<=n;i++)
Addedge(s,i,P[i],0);
for(int j=1;j<=m;j++)
{Addedge(n+tot*(j-1)+1,t,1,0);
cnt[j]=1;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
Addedge(i,n+(j-1)*tot+cnt[j],1,Time[i][j]*cnt[j]);
}
int main(){
read_data();
Build_graph();
printf("%d\n",mincost());
return 0;
}

0 条评论

目前还没有评论...

信息

ID
1726
难度
6
分类
图结构 | 网络流 点击显示
标签
递交数
424
已通过
105
通过率
25%
被复制
2
上传者