zoukankan      html  css  js  c++  java
  • 费用流模板

     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 }
  • 相关阅读:
    C 习题
    gcc
    几何视角看线性方程组解的情况
    JAVA设计模式之工厂模式(简单工厂模式+工厂方法模式)
    为什么重写了equals(),还要重写hashCode()?
    关于ArrayList的越界问题?
    通过实例聊聊Java中的多态
    java异常处理实例分析
    Java: Integer用==比较时127相等128不相等的原因
    Java并发编程:Lock
  • 原文地址:https://www.cnblogs.com/CXCXCXC/p/5207711.html
Copyright © 2011-2022 走看看