费用流模板

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int inf=1e9;
 4 const int N=100,M=1000;
 5 struct node{
 6     int to,rest,next,cost;
 7 }e[M];
 8 int head[N],cnt=1;
 9 inline void addedge(int x,int y,int z,int c){
10     e[++cnt].to=y; e[cnt].rest=z; e[cnt].cost= c; e[cnt].next=head[x];
11     e[++cnt].to=x; e[cnt].rest=0; e[cnt].cost=-c; e[cnt].next=head[y];
12 }
13 int n,m,S,T;
14 int dis[N],pre[N];
15 bool vis[N];
16 int maxflow,mincost;
17 inline bool SPFA(){
18     static queue<int> Q;
19     for(int i=S;i<=T;i++) dis[i]=inf,vis[i]=false;
20     Q.push(S); dis[S]=0; vis[S]=true;
21     while(!Q.empty()){
22         int x=Q.front(); Q.pop();
23         vis[x]=false;
24         for(int i=head[x];i;i=e[i].next){
25             int y=e[i].to;
26             if(e[i].rest&&dis[y]>dis[x]+e[i].cost){
27                 dis[y]=dis[x]+e[i].cost;
28                 pre[y]=i;
29                 if(vis[y]=false){
30                     vis[y]=true;
31                     Q.push(y);
32                 }
33             }
34         }
35     }
36     return dis[T]<inf;
37 }
38 inline void update(){
39     int flow=inf;
40     for(int i=pre[T];i;i=pre[e[i^1].to])
41         flow=min(flow,e[i].rest);
42     for(int i=pre[T];i;i=pre[e[i^1]].to){
43         e[i].rest-=flow;
44         e[i^1].rest+=flow;
45     }
46     maxflow+=flow; mincost+=flow*dis[T];
47 }
48 inline void MCF(){
49     maxflow=mincost=0;
50     while(SPFA()) update();
51     printf("%d %d",maxflow,mincost);
52 }
53 int main(){
54     scanf("%d%d",&n,&m);
55     S=1; T=n;
56     for(int i=1,u,v,z,c;i<=m;i++){
57         scanf("%d%d%d%",&u,&v,&z,&c);
58         addedge(u,v,z,c);
59     }
60     MCF();
61     return 0;
62 }

 

转载于:https://www.cnblogs.com/CXCXCXC/p/5207711.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值