网络流--最小费用最大流MCMF模板

标准大白书式模板

 

 1 #include<stdio.h>        //大概这么多头文件昂

 2 #include<string.h>

 3 #include<vector>

 4 #include<queue>

 5 #include<algorithm>

 6 using namespace std;

 7 const int maxm=10000+100;    //最大点数

 8 const int INF=0x3f3f3f3f;

 9 

10 struct edge{        //边:起点、终点、容量、流量、单位费用

11     int from,to,c,f,cost;

12     edge(int a,int b,int m,int n,int p):from(a),to(b),c(m),f(n),cost(p){}

13 };

14 

15 int aabs(int a){

16     return a>=0?a:-a;

17 }

18 

19 struct MCMF{

20     int m,s,t;

21     vector<edge>e;

22     vector<int>g[maxm];

23     int dis[maxm],a[maxm],p[maxm];

24     bool vis[maxm];

25 

26     void init(int n){        //初始化函数

27         for(int i=0;i<=n;i++)g[i].clear();

28         e.clear();

29     }

30 

31     void add(int a,int b,int c,int v){    //加边函数

32         e.push_back(edge(a,b,c,0,v));

33         e.push_back(edge(b,a,0,0,-v));

34         m=e.size();

35         g[a].push_back(m-2);

36         g[b].push_back(m-1);

37     }

38 

39     bool spfa(int& flow,int& cost){

40         memset(dis,0x3f,sizeof(dis));

41         memset(vis,0,sizeof(vis));

42         queue<int>q;

43         q.push(s);

44         vis[s]=1;

45         dis[s]=0;

46         p[s]=0;

47         a[s]=INF;

48         while(!q.empty()){

49             int u=q.front();q.pop();

50             vis[u]=0;

51             for(int i=0;i<g[u].size();i++){

52                 edge tmp=e[g[u][i]];

53                 if(dis[tmp.to]>dis[u]+tmp.cost&&tmp.c>tmp.f){

54                     dis[tmp.to]=dis[u]+tmp.cost;

55                     p[tmp.to]=g[u][i];

56                     a[tmp.to]=min(a[u],tmp.c-tmp.f);

57                     if(!vis[tmp.to]){

58                         q.push(tmp.to);

59                         vis[tmp.to]=1;

60                     }

61                 }

62             }

63         }

64         if(dis[t]==INF)return 0;

65         flow+=a[t];

66         cost+=dis[t]*a[t];

67         int u=t;

68         while(u!=s){

69             e[p[u]].f+=a[t];

70             e[p[u]^1].f-=a[t];

71             u=e[p[u]].from;

72         }

73         return 1;

74     }

75 

76     int MF(int s,int t){        调用的计算最小费用函数

77         this->s=s;this->t=t;

78         int flow=0,cost=0;

79         while(spfa(flow,cost));

80         return cost;

81     }

82 

83 };

 

你可能感兴趣的:(网络流)