最小费用最大流
邻接矩阵+SPFA
bool spfa(){
int u,v;
memset(pre,0,sizeof pre);
memset(dist,0x7f,sizeof dist);
dist[S]=0;
vis[S]=1;
q.push(S);
while(!q.empty()){
u=q.front();
q.pop();
vis[u]=0;
for(v=S;v<=T;v++)
if(cap[u][v].c&&dist[v]>cap[u][v].wt+dist[u]){
dist[v]=cap[u][v].wt+dist[u];
pre[v]=u;
if(!vis[v]){
vis[v]=1;
q.push(v);
}
}
}
if(dist[T]==INF)
return 0;
else
return 1;
}
void mcmf(){
int delta,p;
while(spfa()){
delta=INF;
for(p=T;pre[p];p=pre[p])
delta=min(delta,cap[pre[p]][p].c);
for(p=T;pre[p];p=pre[p]){
cost+=cap[pre[p]][p].wt*delta;
cap[pre[p]][p].c-=delta;
cap[p][pre[p]].c+=delta;
}
}
}
邻接表+SPFA(SLF+LLL)
bool spfa(){
memset(dist,0x7f,sizeof dist);
int u,v,len,cnt;
len=cnt=0;
q.push_back(S);
vis[S]=1;
dist[S]=0;
while(!q.empty()){
u=q.front();
q.pop_front();
if(dist[u]*len>cnt){
q.push_back(u);
continue;
}
vis[u]=0;
len--,cnt-=dist[u];
for(node *p=adj[u];p;p=p->next){
v=p->v;
if(p->cap&&dist[v]>dist[u]+p->wt){
pre[v]=p;
if(vis[v])
cnt-=dist[v];
dist[v]=dist[u]+p->wt;
cnt+=dist[v];
if(!vis[v]){
if(q.empty()||dist[v]>dist[q.front()])
q.push_back(v);
else
q.push_front(v);
vis[v]=1;
len++;
}
}
}
}
if(dist[T]==INF)
return 0;
return 1;
}
void mcmf(){
int u,delta;
while(spfa()){
delta=INF;
for(u=T;u!=S;u=pre[u]->back->v)
delta=min(delta,pre[u]->cap);
for(u=T;u!=S;u=pre[u]->back->v){
cost+=delta*pre[u]->wt;
pre[u]->cap-=delta;
pre[u]->back->cap+=delta;
}
}
}