zoukankan      html  css  js  c++  java
  • 【费用流】【Next Array】费用流模板(spfa版)

     1 #include<cstdio>
     2 #include<algorithm>
     3 #include<cstring>
     4 #include<queue>
     5 using namespace std;
     6 #define MAXN 501
     7 #define MAXM 50001
     8 #define INF 2147483647
     9 int S,T,n,m;
    10 int en,u[MAXM],v[MAXM],first[MAXN],next[MAXM],cap[MAXM],cost[MAXM];//Next Array
    11 bool inq[MAXN];
    12 int d[MAXN]/*spfa*/,p[MAXN]/*spfa*/,a[MAXN]/*可改进量*/;
    13 queue<int>q;
    14 void Init_MCMF(){memset(first,-1,sizeof(first));en=0;}
    15 void AddEdge(const int &U,const int &V,const int &W,const int &C)
    16 {
    17     u[en]=U; v[en]=V; cap[en]=W; cost[en]=C;
    18     next[en]=first[U]; first[U]=en++;
    19     u[en]=V; v[en]=U; cap[en]=0; cost[en]=-C;
    20     next[en]=first[V]; first[V]=en++;
    21 }
    22 bool Spfa(int &Flow,int &Cost)
    23 {
    24     memset(d,0x7f,sizeof(d));
    25     memset(inq,0,sizeof(inq));
    26     d[S]=0; inq[S]=1; p[S]=0; a[S]=INF; q.push(S);
    27     while(!q.empty())
    28       {
    29           int U=q.front(); q.pop(); inq[U]=0;
    30           for(int i=first[U];i!=-1;i=next[i])
    31             if(cap[i] && d[v[i]]>d[U]+cost[i])
    32               {
    33                 d[v[i]]=d[U]+cost[i];
    34                 p[v[i]]=i;
    35                 a[v[i]]=min(a[U],cap[i]);
    36                 if(!inq[v[i]]) {q.push(v[i]); inq[v[i]]=1;}
    37               }
    38       }
    39     if(d[T]>2000000000) return 0;
    40     Flow+=a[T]; Cost+=d[T]*a[T]; int U=T;
    41     while(U!=S)
    42       {
    43           cap[p[U]]-=a[T]; cap[p[U]^1]+=a[T];
    44           U=u[p[U]];
    45       }
    46     return 1;
    47 }
    48 int Mincost()
    49 {
    50     int Flow=0,Cost=0;
    51     while(Spfa(Flow,Cost));
    52     return Cost;
    53 }
  • 相关阅读:
    史上最全Html与CSS布局技巧
    Discuz! X的CSS加载机制
    关于input框只能输入纯数字问题
    对象的数据属性
    vue中将光标定位到Input上的问题
    端口占用问题解决方案
    el-button如何消除右边计数样式
    如何改变vscode的背景颜色
    为什么——要实例化对象?
    call()&apply()
  • 原文地址:https://www.cnblogs.com/autsky-jadek/p/4149096.html
Copyright © 2011-2022 走看看