//代码MCMF和SPFA部分直接拷贝来源于AOJ581
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int NN=250;
const int MM=50000;
const int INF=0x3fffffff;
struct Edge{
int u,v,cost,flow,next;
}edge[MM];
int head[NN];
int n,m,S,T,NV,ecnt;
void init()
{
S=0; T=2*n+1;
NV=T+1;
ecnt=1;
for (int i=0; i<NV; i++) head[i]=0;
}
void addedge(int u,int v,int cost,int flow)
{
ecnt++;
edge[ecnt].u=u;
edge[ecnt].v=v;
edge[ecnt].cost=cost;
edge[ecnt].flow=flow;
edge[ecnt].next=head[u];
head[u]=ecnt;
ecnt++;
edge[ecnt].u=v;
edge[ecnt].v=u;
edge[ecnt].cost=-cost;
edge[ecnt].flow=0;
edge[ecnt].next=head[v];
head[v]=ecnt;
}
void build_graph()
{
int x,y,z;
for (int i=1; i<=n; i++)
{
addedge(S,i,0,1);
addedge(i+n,T,0,1);
}
for (int i=1; i<=m; i++)
{
scanf("%d%d%d",&x,&y,&z);
addedge(x,y+n,z,1);
}
}
bool used[NN];
int dis[NN],p[NN];
bool SPFA(void){
queue<int> q;
for (int i=1; i<NV; i++) dis[i]=INF;
dis[S]=0;
q.push(S);
p[S]=-1;
while (!q.empty()){
int u=q.front();
used[u]=false; //不从while循环中直接退出的SPFA的used只要初始化一次就行
q.pop();
for (int i=head[u]; i; i=edge[i].next){
int v=edge[i].v;
if (edge[i].flow>0 && dis[v]>dis[u]+edge[i].cost){
dis[v]=dis[u]+edge[i].cost;
p[v]=i;
if (!used[v]){
used[v]=true;
q.push(v);
}
}
}
}
if (dis[T]==INF) return false;
else return true;
}
int MCMF(){
int max_flow=0;
int min_cost=0;
while (SPFA()){
int flow=INF;
int u,v;
for (v=T; p[v]!=-1; v=u){
u=edge[p[v]].u;
flow=flow<edge[p[v]].flow ? flow: edge[p[v]].flow;
}
for (v=T; p[v]!=-1; v=u){
u=edge[p[v]].u;
edge[p[v]].flow-=flow;
edge[p[v]^1].flow+=flow;
}
max_flow+=flow;
min_cost+=dis[T]*flow;
}
if (max_flow==n) return min_cost;
else return -1;
}
int main()
{
while (scanf("%d%d",&n,&m)!=EOF)
{
init();
build_graph();
printf("%d\n",MCMF());
}
return 0;
}
HDOJ1853-费用流(圈,拆点)
最新推荐文章于 2017-05-01 20:41:32 发布