SPFA费用流模板

#include<bits/stdc++.h>  
//#pragma comment(linker, "/STACK:1024000000,1024000000")   
#include<stdio.h>  
#include<algorithm>  
#include<queue>  
#include<string.h>  
#include<iostream>  
#include<math.h>  
#include<set>  
#include<map>  
#include<vector>  
#include<iomanip>  
using namespace std;  
#define ll long long  
#define pb push_back  
#define FOR(a) for(int i=1;i<=a;i++)  
const int inf=0x3f3f3f3f;  
const int maxn=4e5+9;    
  
struct EDGE{  
    int to,next,cap,flow,cost;  
}G[maxn];  
int head[maxn],tot;  
int pre[maxn],dis[maxn];  
int vis[maxn];  
  
int source,sink;  
int num_nodes;  
  
void init(){  
    tot=0;  
    memset(head,-1,sizeof head);  
}  
void addedge(int u,int v,int cap,int cost){  
    G[tot]=(EDGE){v,head[u],cap,0,cost};head[u]=tot++;  
    G[tot]=(EDGE){u,head[v],0,0,-cost} ;head[v]=tot++;  
}  
int spfa(int s,int t){  
    queue<int>Q;  
    for(int i=0;i<=num_nodes;i++){dis[i]=inf;vis[i]=0;pre[i]=-1;}  //偶尔要根据点的标记顺序修改一下
    dis[s]=0;vis[s]=1;  
    Q.push(s);  
    while(!Q.empty()){  
        int u=Q.front();Q.pop();vis[u]=0;  
        for(int i=head[u];~i;i=G[i].next){  
            int v=G[i].to;  
            if(G[i].cap>G[i].flow && dis[v]>dis[u]+G[i].cost){  
                dis[v]=dis[u]+G[i].cost;  
                pre[v]=i;  
                if(!vis[v]){  
                    vis[v]=1;  
                    Q.push(v);  
                }  
            }  
        }  
    }  
    if(pre[t]==-1)return 0;  
    return 1;  
}  
int mcmf(int &cost){  
    int s=source,t=sink;  
    int flow=0;  
    cost=0;  
    while(spfa(s,t)){  
        int a=inf;  
        for(int i=pre[t];~i;i=pre[G[i^1].to]){  
            a=min(a,G[i].cap-G[i].flow);  
        }  
        for(int i=pre[t];~i;i=pre[G[i^1].to]){  
            G[i].flow+=a;  
            G[i^1].flow-=a;  
            cost+=G[i].cost*a;  
        }  
        flow+=a;  
    }  
    return flow;  
}
/*******
init,num_nodes,source,sink
*******/


posted @ 2017-07-04 21:22  Drenight  阅读(140)  评论(0编辑  收藏  举报