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

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstdio>
     4 #include<cstring>
     5 #include<cmath>
     6 #include<queue>
     7 #define inf 2147483647
     8 using namespace std;
     9 struct data
    10 {
    11     int from,to,next,cup,flow,cost;
    12     data(){from=-1,to=-1,next=-1,cup=-1,flow=-1,cost=-1;}
    13 }e[200];
    14 int vis[200],head[200],d[200],p[200],a[200];
    15 int cnt,flow,cost;
    16 int n,m;
    17 void add(int u,int v,int w,int c)
    18 {e[cnt].from=u,e[cnt].to=v,e[cnt].next=head[u],head[u]=cnt,e[cnt].cup=w,e[cnt].flow=0,e[cnt].cost=c,cnt++;}
    19 bool spfa(int s,int t)
    20 {
    21     memset(vis,0,sizeof(vis));
    22     for(int i=1;i<=n;i++) d[i]=inf;
    23     queue<int>q;
    24     q.push(s);
    25     d[s]=0,vis[s]=1,p[s]=0,a[s]=inf;
    26     while(!q.empty())
    27     {
    28         int now=q.front();
    29         q.pop();
    30         vis[now]=0;
    31         for(int i=head[now];i>=0;i=e[i].next)
    32         {
    33             if(e[i].cup>e[i].flow&&d[e[i].from]<inf&&d[e[i].to]>d[e[i].from]+e[i].cost)
    34             {
    35                 d[e[i].to]=d[e[i].from]+e[i].cost;
    36                 p[e[i].to]=i;
    37                 a[e[i].to]=min(a[e[i].from],e[i].cup-e[i].flow);
    38                 if(!vis[e[i].to])
    39                 {
    40                     q.push(e[i].to);
    41                     vis[e[i].to]=1;
    42                 }
    43             }
    44         }
    45     }
    46     if(d[t]==inf) return false;
    47     flow+=a[t];
    48     cost+=d[t]*a[t];
    49     int now=t;
    50     while(now!=s)
    51     {
    52         e[p[now]].flow+=a[t];
    53         e[p[now]^1].flow-=a[t];
    54         now=e[p[now]].from;
    55     }
    56     return true;
    57 }
    58 int main()
    59 {
    60     memset(head,-1,sizeof(head));
    61     
    62     scanf("%d%d",&n,&m);
    63     for(int i=1;i<=m;i++)
    64     {
    65         int u,v,w,c;
    66         scanf("%d%d%d%d",&u,&v,&w,&c);
    67         add(u,v,w,c);
    68         add(v,u,0,-c);
    69     }
    70     int s,t;
    71     scanf("%d%d",&s,&t);
    72     while(spfa(s,t));
    73     cout<<flow<<' '<<cost;
    74 }
    View Code
    O(∩_∩)O~ (*^__^*) 嘻嘻…… O(∩_∩)O哈哈~
  • 相关阅读:
    C++程序设计入门--前言
    C++ string_view 的坑
    从OGRE,GAMEPLAY3D,COCOS2D-X看开源
    抽烟解闷的程序员
    一个团队应该是什么样
    准备开始接手公司的项目
    两位印象深刻的同事
    一段故事结束,一段生活开始
    starling性能优化总结(毫无疑问还是转载)
    知道端口号如何查看应用位置
  • 原文地址:https://www.cnblogs.com/wls001/p/5598860.html
Copyright © 2011-2022 走看看