费用流模板

 

 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 }

 

posted @ 2016-02-22 17:19  CXCXCXC  阅读(209)  评论(0编辑  收藏  举报